14

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

Gibolt
  • 42,564
  • 15
  • 187
  • 127
lacas
  • 13,928
  • 30
  • 109
  • 183

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,492
  • 2
  • 26
  • 32
17

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

Handler#postDelayed(Runnable, Long)

saiyancoder
  • 1,285
  • 2
  • 13
  • 20
Juhani
  • 5,076
  • 5
  • 33
  • 35
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,394
  • 3
  • 30
  • 36
  • 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
  • 11,008
  • 6
  • 50
  • 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
  • 219
  • 1
  • 10