Question

i saw this approach :

TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
        MyMethod();
    }
};

Timer timer = new Timer(true);
timer.schedule(timerTask, 0, 7200000); 

1 . is this the best approach ?

2 . how can i make sure this method wont "die" ?

note : i don't need this method to work on background if the application is closed so no need to do service or something like this .

Was it helpful?

Solution 2

this was the answer i was looking for , once the application is not running this will stop as i wanted .

final Handler handler = new Handler();
    Runnable runnable = new Runnable() {
           @Override
           public void run() {
              L.e("Called");
              handler.postDelayed(this, 7200000);
           }
        };
        handler.postDelayed(runnable, 7200000);

OTHER TIPS

I think this method can be improved if you use AlarmManager instead. You can set up an recurring alarm for every 2 hrs, then have a BroadCast Receiver to receive the alarm, here you can do your stuff. This will not die as long as the device is not rebooted. If it does reboot, then you need to detect the device start and re-set your recurring alarm.

Having said that, the above method seems more reliable than TimerTask, if your polling duration is as high as 2 hrs. After 2 hrs your app may not even be running, its likely that OS would have killed it by then, so this code will not work for such a long duration. I think TimerTask method is more suitable for poll duration in order of seconds. In your case you are better of using AlarmManager and RecurringAlarm.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top