TimerTask vs Thread.sleep vs Handler postDelayed – most accurate to call function every N milliseconds?

There are some disadvantages of using Timer It creates only single thread to execute the tasks and if a task takes too long to run, other tasks suffer. It does not handle exceptions thrown by tasks and thread just terminates, which affects other scheduled tasks and they are never run ScheduledThreadPoolExecutor deals properly with all … Read more

How do you use a TimerTask to run a thread?

I have implemented something like this and it works fine: private Timer mTimer1; private TimerTask mTt1; private Handler mTimerHandler = new Handler(); private void stopTimer(){ if(mTimer1 != null){ mTimer1.cancel(); mTimer1.purge(); } } private void startTimer(){ mTimer1 = new Timer(); mTt1 = new TimerTask() { public void run() { mTimerHandler.post(new Runnable() { public void run(){ //TODO … Read more

Where do I create and use ScheduledThreadPoolExecutor, TimerTask, or Handler?

I prefer to use ScheduledThreadPoolExecutor. Generally, if I understand your requirements correctly, all these can be implemented in your activity, TimerTask and Handler are not needed, see sample code below: public class MyActivity extends Activity { private ScheduledExecutorService scheduleTaskExecutor; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); scheduleTaskExecutor= Executors.newScheduledThreadPool(5); // This schedule a task to run every … Read more

Timertask or Handler

Handler is better than TimerTask. The Java TimerTask and the Android Handler both allow you to schedule delayed and repeated tasks on background threads. However, the literature overwhelmingly recommends using Handler over TimerTask in Android (see here, here, here, here, here, and here). Some of reported problems with TimerTask include: Can’t update the UI thread … Read more

How to execute Async task repeatedly after fixed time intervals

public void callAsynchronousTask() { final Handler handler = new Handler(); Timer timer = new Timer(); TimerTask doAsynchronousTask = new TimerTask() { @Override public void run() { handler.post(new Runnable() { public void run() { try { PerformBackgroundTask performBackgroundTask = new PerformBackgroundTask(); // PerformBackgroundTask this class is the class that extends AsynchTask performBackgroundTask.execute(); } catch (Exception e) … Read more

How to run certain task every day at a particular time using ScheduledExecutorService?

As with the present java SE 8 release with it’s excellent date time API with java.time these kind of calculation can be done more easily instead of using java.util.Calendar and java.util.Date. Use date time class’s i.e. LocalDateTime of this new API Use ZonedDateTime class to handle Time Zone specific calculation including Daylight Saving issues. You … Read more