A handler or timer for scheduling fixed-speed tasks

I am working on an application that requires it to go online every x minutes and check for new data. To prevent heavy use of network and data, the task must be performed at a fixed speed, but what is the best use approach for such a solution? A Handleror Timerobject?

+4
source share
6 answers

There are some disadvantages to using a timer

  • It creates only one thread to perform tasks, and if the task takes too much time to perform other tasks.
  • It does not handle the exceptions set by tasks, and the thread just ends, which affects other scheduled tasks, and they never run.

While on the other hand, it ScheduledThreadPoolExecutorcopes with all these problems correctly, and it makes no sense to use a timer. In your case two methods can be used

  • scheduleAtFixedRate (...)

  • scheduleWithFixedDelay (..)

    class LongRunningTask implements Runnable {
    
      @Override
      public void run() {
        System.out.println("Hello world");
      } 
    }
    
    ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
    long period = 100; // the period between successive executions
    exec.scheduleAtFixedRate(new LongRunningTask (), 0, duration, TimeUnit.MICROSECONDS);
    long delay = 100; //the delay between the termination of one execution and the commencement of the next
    exec.scheduleWithFixedDelay(new MyTask(), 0, duration, TimeUnit.MICROSECONDS);
    

And to cancel the Contractor use this - ScheduledFuture

// schedule long running task in 2 minutes:
ScheduledFuture scheduleFuture = exec.scheduleAtFixedRate(new MyTask(), 0, duration, TimeUnit.MICROSECONDS);

... ...
// At some point in the future, if you want to cancel scheduled task:
scheduleFuture.cancel(true);
+2
source

AlarmReceiver . - , , , , Android , * . , .

0

, Alarm manager, broadcast Reciever, X , .

, timer handler, . , , .

- handler timer, , . handlers Runnable Messeges.

0

Alarm, , ScheduledThreadPoolExecutor.

:

Android

, , ( , , SMS, , ?) thread AsyncTask ? , ...

0

, , . . :

final Runnable updateRunnable = new Runnable() {
    public void run() {
        // Fetch the date here in an async task 
    }
};

final Handler myHandler = new Handler();
private Timer myTimer;

private void updateUI() {
   myHandler.post(updateRunnable);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  // ... other things here

  myTimer = new Timer();
  myTimer.schedule(new TimerTask() {
     @Override
     public void run() {
        updateUI(); // Here you can update the UI as well
     }
  }, 0, 10000); // 10000 is in miliseconds, this executes every 10 seconds

  // ... more other things here

}
0

. postDelayed, .

In fact, the use of Handler is officially recommended by timer or timer: http://android-developers.blogspot.ru/2007/11/stitch-in-time.html

0
source

All Articles