How to run an async task for every x mins in android?

前端 未结 9 1048
长发绾君心
长发绾君心 2020-11-27 12:28

how to run the async task at specific time? (I want to run it every 2 mins)

I tried using post delayed but it\'s not working?

    tvData.postDelayed         


        
相关标签:
9条回答
  • 2020-11-27 13:19

    You can use Time with Handler and TimerTask

      final Handler handler = new Handler();
            Timer timer = new Timer();
            TimerTask backtask = new TimerTask() {
                @Override
                public void run() {
                    handler.post(new Runnable() {
                        public void run() {
                            try {
                                //To task in this. Can do network operation Also
                                Log.d("check","Check Run" );
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                            }
                        }
                    });
                }
            };
            timer.schedule(backtask , 0, 20000); //execute in every 20000 ms*/
    

    You can check logcat to verify whether is running or not using 'check' tag name

    0 讨论(0)
  • 2020-11-27 13:22

    You can use handler if you want to initiate something every X seconds. Handler is good because you don't need extra thread to keep tracking when firing the event. Here is a short snippet:

    private final static int INTERVAL = 1000 * 60 * 2; //2 minutes
    Handler mHandler = new Handler();
    
    Runnable mHandlerTask = new Runnable()
    {
         @Override 
         public void run() {
              doSomething();
              mHandler.postDelayed(mHandlerTask, INTERVAL);
         }
    };
    
    void startRepeatingTask()
    {
        mHandlerTask.run(); 
    }
    
    void stopRepeatingTask()
    {
        mHandler.removeCallbacks(mHandlerTask);
    }
    

    Note that doSomething should not take long (something like update position of audio playback in UI). If it can potentially take some time (like downloading or uploading to the web), then you should use ScheduledExecutorService's scheduleWithFixedDelay function instead.

    0 讨论(0)
  • 2020-11-27 13:24

    you can use TimerTask instead of AsyncTask.

    ex:

    Timer myTimer = new Timer("MyTimer", true);
    myTimer.scheduleAtFixedRate(new MyTask(), ASAP, TWO_MINUTES);
    
    
    private class MyTask extends TimerTask {
    
        public void run(){
          readWebPage();
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题