0

I created a periodic weekly work manager worker to delete the files my application creates.

    WorkManager workManager = WorkManager.getInstance(context);
    workManager.cancelAllWorkByTag(workTag);
    PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(DeleteFileWorker.class, 7, TimeUnit.DAYS).addTag(workTag).build();
    workManager.enqueueUniquePeriodicWork(workTag, ExistingPeriodicWorkPolicy.REPLACE, periodicWorkRequest);

Here, I'm telling the worker to run once a week or once each 7 days. But when is it going to run? Can I control the approximate hour?

My guess is it will run the first time it can when the application starts and the second time will be at the same hour(approximately) and day as the first launch.

Can I configure it to run around 12 AM? It doesn't need to be an exact time.

Maor Hadad
  • 1,850
  • 21
  • 36

1 Answers1

0

You can't have strong expectations with WM. Please check here the Constraints section:

https://developer.android.com/topic/libraries/architecture/workmanager/how-to/debugging#use-alb-shell0dumpsys-jobscheduler

Also, let me point one thing - what you have "is not" a periodic Work.

What WM does is that it creates a single job in the JobScheduler and it has an extra Constrain - TIMING_DELAY. At the same time besides explicit constraints, you have implicit ones coming from the system. So for a work to be executed all the right conditions need to be in places related to battery optimizations, doze, power buckets, etc. So you can't say for sure when it will happen.

And when the work is executed successfully - WM creates a new job in the JS with TIMING_DELAY again the time you see as a period. So if you put 24 hours as a "period", but the conditions are not right for your work to be executed and it is delayed 10 hours - you will have a 34 hours span between 2 works.

Also, you know it is Android - on every device it is different. But you can improve this by asking your application to be excluded from battery optimization.

https://developer.android.com/training/monitoring-device-state/doze-standby#support_for_other_use_cases

Here more on what to expect from each device:

https://dontkillmyapp.com/

Also, have it in mind that you have a specific amount of time depending on your power bucket to run per day. I guess you are not using Network, but if you do - there is also a set amount of time to use the network. Without battery optimization disabled you might hit some of these:

https://developer.android.com/topic/performance/power/power-details

Yavor Mitev
  • 1,363
  • 1
  • 10
  • 22