14

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

Gibolt
  • 33,561
  • 12
  • 157
  • 107
lacas
  • 13,555
  • 29
  • 107
  • 179

5 Answers5

18

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

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        new MyAsyncTask().execute();
    }
}, 3000);
Facundo Olano
  • 2,402
  • 2
  • 25
  • 32
17

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

Handler#postDelayed(Runnable, Long)

saiyancoder
  • 1,237
  • 1
  • 13
  • 20
Juhani
  • 5,008
  • 5
  • 31
  • 34
13

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

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

        // run AsyncTask here.    


    }
}, 3000);
mani
  • 3,226
  • 2
  • 28
  • 35
  • 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 08 '17 at 01:13
4

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

mHandler.postDelayed(handleMyAsyncTask, 1000*3);
Zelimir
  • 10,918
  • 5
  • 47
  • 45
0

Use CountDownTimer.

  new CountDownTimer(3000, 1000) {

        public void onTick(long millisUntilFinished) {

           //do task which continuously updates

        }

        public void onFinish() {

           //Do your task
         
        }

    }.start();

3000 is total seconds and 1000 is timer tick on that time means on above case timer ticks 3 time.

Rahul
  • 199
  • 1
  • 10