The best way to set a recurring task

I have a method in my application that I want it to be called repeatedly depending on what the user selects. for example, if the user selects each hour, the action launches a method that is called every hour. I would like to know how best to plan this recurring task.

I experimented with timer and timer jobs, but for some reason it doesn't work when I use the java calendar class with it, for example:

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

and from what I read, Handlers are not suitable for this multithreaded task. I would have to use an alarm manager for this, and why would this code not execute correctly? thank

+3
source share
1 answer

You want AlarmManager and setRepeating or setInexactRepeating calls.

There you plan the intention that should be delivered to your application, and write a receiver of intentions to process it. Thus, the activation of your application is completely dependent on the Android system, and your application does not need to run for the whole hour, which it just waits to activate.

If for some odd reason you need your code running between timer calls, you need to keep the background service, but you will still use AlarmManager to wake it up.

+3
source

Source: https://habr.com/ru/post/1772485/


All Articles