Reputation: 329
Hello everyone and good Friday,
I know this can seem like a duplicate question but it ISN'T and i'll explain you why:
There are serveral ways to execute a task at scheduled time, like TimerTask or ScheduleExecutorService, but none of them is good for what i'm trying to do becouse these methods all works like this:
But i don't want my code to be run the first time and again after scheduled time, i want that my code gets executed ALWAYS every scheduled time, even the first time.
There's also another problem: What happens if android stops the Background service? I added a Restarter receiver so the service gets restarted and so,
What happens when the Background service gets restarted? Since the TimerTask or ScheduleExecutorService gets killed and started again, the above mentioned steps will repeat from 1 to 2.
What is the result?
Let's suppose i want to run a Task every 3 minutes but android kills my service after only 30 seconds: Since the first time the code inside void run() gets executed, the result is that my code gets executed after 30 seconds and not 3 miutes!
So my question is: Is it possible to run a task or a method in an Android Background Service every X minutes avoiding the mentioned problems?
Thanks!
Upvotes: 3
Views: 1278
Reputation: 885
Yes, I believe you are bringing the wrong tool for the job. You could use JobScheduler
or AlarmManager
perhaps to achieve your desired results. But what you should be using is WorkManager
.
WorkManager
is highly configurable and will allow you to create a PeriodicWorkRequest
or a OneTimeWorkRequest
these are guaranteed to succeed. PeriodicWorkRequest
will fire when you schedule the work, as well as when you have specified in the timer. It will execute in the background even if the app is closed or backgrounded. If you didn't want your task to execute immediately you can use a PWR with a FlexInterval. See the docs below for more info.
For example, I created two PeriodicWorkRequests that refresh services and keeps the user logged in always by renewing their token. When the user authenticates the PeriodicWorkRequest
is created. Normally it will fire your work immediately which sounds like your desired use case. However, in my case, I didn't need it to fire right away as they have just received and cached this information so I utilized the FlexInterval. When the app is backgrounded or closed, the workers continue to refresh services every 12 hours and refresh the token every 6. It works like a charm.
Upvotes: 1