Periodicworkrequest With Workmanager
Solution 1:
You can achieve this by using flex period in PeriodicWorkRequest.Builder. As example, if you want run your Worker within 15 minutes at the end of repeat interval (let's say 8 hours), code will look like this:
val periodicRefreshRequest = PeriodicWorkRequest.Builder(
RefreshWorker::class.java, // Your worker class8, // repeating interval
TimeUnit.HOURS,
15, // flex interval - worker will run somewhen within this period of time, but at the end of repeating interval
TimeUnit.MINUTES
)
Solution 2:
you need to add initialDelay to the builder
funscheduleRecurringFetchWeatherSyncUsingWorker() {
val constraints: Constraints = Constraints.Builder().apply {
setRequiredNetworkType(NetworkType.CONNECTED)
setRequiresBatteryNotLow(true)
}.build()
val request: PeriodicWorkRequest = PeriodicWorkRequest.Builder(
MySimpleWorker::class.java, 3, TimeUnit.HOURS, 1, TimeUnit.HOURS)
.setConstraints(constraints)
.setInitialDelay(2, TimeUnit.HOURS)
.setBackoffCriteria(BackoffPolicy.LINEAR, 1, TimeUnit.HOURS)
.build()
mWorkManager.enqueueUniquePeriodicWork(
TAG_WORK_NAME,
ExistingPeriodicWorkPolicy.KEEP,
request
)
}
Solution 3:
Your code always reschedule the work, so you could change the work parameters as you want
instance.enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.REPLACE, build);
if you want to keep the work with same parameters (even after reboot), without any changes, use:
instance.enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.KEEP, build);
in the case it will be scheduled it only if the work is not engueued already.
For to stop the work task, use
// cancel the unique work
instance.cancelUniqueWork(TAG);
// clear all finished or cancelled tasks from the WorkManager
instance.pruneWork();
Btw, I think its not good approach to use same TAG as the unigue work id and as task tag. In case you need unique work - you dont really need the task tag at all. The task tag is for cases then you want to have several tasks
Solution 4:
To delay the task you could use setInitialDelay.
We have used setInitialDelay to ensure the notification is triggered on the day of the event rather than immediately. This delay is calculated by a separate method which returns the amount of milliseconds between now and when the notification should trigger (at noon on the date of the event). Please note that this delay is not always accurate! Due to how modern Android works, your work can be delayed by a number of factors, so be aware of this for very time sensitive purposes.
All the info is in this post. https://medium.com/@eydryan/scheduling-notifications-on-android-with-workmanager-6d84b7f64613
Post a Comment for "Periodicworkrequest With Workmanager"