How can an AsyncTask be started after a 3 second delay?

  • How important is it that the task persist through app restarts? – Mooing Duck Nov 8 '17 at 1:13

You can use Handler for that. Use postDelayed(Runnable, long) for that.

Handler#postDelayed(Runnable, Long)


Using handlers as suggested in the other answers, the actual code is:

new Handler().postDelayed(new Runnable() {
    public void run() {
        new MyAsyncTask().execute();
}, 3000);

You can use this piece of code to run after a 3 sec delay.

new Timer().schedule(new TimerTask() {          
    public void run() {

        // run AsyncTask here.    

}, 3000);
  • what if after 1sec application is closed? i mean the application is completely destroyed? will this timer still run after 3 sec... i am asking bcz my need is to run AsyncTask even if the app is closed.... – kumar Apr 20 '16 at 14:31
  • No, it will not run. If you need to persist through app restarts, use alarms. – Mooing Duck Nov 8 '17 at 1:13

Use Handler class, and define Runnable handleMyAsyncTask that will contain code executed after 3000 msec delay:

mHandler.postDelayed(handleMyAsyncTask, 1000*3);

Your Answer

