3

i have a method in my app that i want to be called repeatedly depending on what the user chooses. like if every hour is chosen by the user, the activity fires a method that is being called every hour. i would like to know the best way to schedule this repeated task.

i have been experimenting with Timers and Timer task, but for some reason it doesn't not seem to work when i use the java calendar class with it, like this:

    Calendar c1 = Calendar.getInstance();
          c1.add(Calendar.SECOND, 30);    
  updateTimer.scheduleAtFixedRate(cleanCompletedCache, c1.getTimeInMillis(),hour );

and from what i have been reading, Handlers are not suitable for this multi-repeating task. would i have to use an alarm manager for this and why won't the above code execute correctly? thanks

irobotxx
  • 5,963
  • 11
  • 62
  • 91
  • I had a similar problem so I just use the following code to keep setting new calls at a specific time (SHORT_UPDATE_INTERVAL is a variable I created not a system constant). timer.schedule(new TimerTask() { @Override public void run() { // call procedures here timerEvent(); } }, SHORT_UPDATE_INTERVAL); – Jim Nov 01 '10 at 21:54
  • thanks would check on that method. but i think i have also seen a way to do it with handlers. thanks anyway – irobotxx Nov 02 '10 at 11:04

1 Answers1

3

You want the AlarmManager and it's setRepeating or setInexactRepeating calls.

There you schedule an Intent to be delivered to your application, and write an intent receiver to process it. This way, the activation of your application is entirely the responsibility of the Android system, and your application does not need to run for the entire hour it is just waiting to activate.

If, for some odd reason, you would need your code running between timer invocations, you need to keep a background service running, but you'd still use AlarmManager to get the wakeup.

Nakedible
  • 4,067
  • 7
  • 34
  • 40