how to call a function every 5 minutes?

Viewed 6167

I need to call the speak method every 5 minutes, then i want to run in background the async method called callspeak, that calls back the speak method(a public method of a different class). It has to loop every 5 minutes

    class callSpeak extends AsyncTask<String, Void, String> {
    activityAudio a = new activityAudio();
    @Override
    protected String doInBackground(String... strings) {

        try
        {
         while (true){
               a.speak();
                Thread.sleep(300000);
            }
        }
        catch (InterruptedException e)
        {e.getMessage();}
      return null;
    }

}
3 Answers

If you want to run the method only when the app is open, you can simply use TimerTask.

Timer myTimer = new Timer ();
TimerTask myTask = new TimerTask () {
    @Override
    public void run () {
        // your code 
        callSpeak().execute() // Your method
    }
};

myTimer.scheduleAtFixedRate(myTask , 0l, 5 * (60*1000)); // Runs every 5 mins

If you want to run it in background even if app is not running, you can use AlarmManager and repeat the task every 5 mins.

Hope it helps

You can do like this:

Handler mHandler = new Handler();

Runnable mRunnableTask = new Runnable()
{
     @Override 
     public void run() {
          doSomething();
          // this will repeat this task again at specified time interval
          mHandler.postDelayed(this, yourDesiredInterval);
     }
};

// Call this to start the task first time
mHandler.postDelayed(mRunnableTask, yourDesiredInterval);

Don't forget to remove the callbacks from handler when you no longer need it.

The latest and the most efficient way to perform this, even if you come out of the activitiy or close the app is to implement the WorkManager from the AndroidX Architecture.

You can find more details here from the official documentation: Schedule tasks with WorkManager

Related