I have an worker to do a periodical task. and this worker is called in an activity on create. Every time the activity open there is a new instance created and do the same task in same time in multiple times. I called the task like this
task = new PeriodicWorkRequest.Builder(BackgroundTask.class, 1000000, TimeUnit.MILLISECONDS).build();
WorkManager.getInstance().enqueue(task);
how to avoid creating multiple instance? if there is no worker running i need to call the instance on create of the activity.
Stop a running Worker You explicitly asked for it to be cancelled (by calling WorkManager. cancelWorkById(UUID) , for example). In the case of unique work, you explicitly enqueued a new WorkRequest with an ExistingWorkPolicy of REPLACE . The old WorkRequest is immediately considered cancelled.
This second interval (the flexInterval) it's positioned at the end of the repetition interval itself. Let's look at an example. Imagine you want to build a periodic Work request with a 30 minutes period. You can specify a flexInterval, smaller than this period, say a 15 minute flexInterval.
public static OneTimeWorkRequest create(String id) { Data inputData = new Data. Builder() . putString(TASK_ID, id) . build(); return new OneTimeWorkRequest.
Use WorkManager for reliable workWorkManager is intended for work that is required to run reliably even if the user navigates off a screen, the app exits, or the device restarts. For example: Sending logs or analytics to backend services. Periodically syncing application data with a server.
You can use the fun WorkManager.enqueueUniquePeriodicWork
This function needs 3 params:
tag
(string) so it would look for other previously created work requests with this tagstrategy
to use when finding other previously created work requests. You can either replace the previous work or keep itwork request
For example in a kotlin project where I needed a location-capturing work to run every some time, I have created a fun that started the work like this:
fun init(force: Boolean = false) {
//START THE WORKER
WorkManager.getInstance()
.enqueueUniquePeriodicWork(
"locations",
if (force) ExistingPeriodicWorkPolicy.REPLACE else ExistingPeriodicWorkPolicy.KEEP,
PeriodicWorkRequest.Builder(
LocationsWorker::class.java,
PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
TimeUnit.MILLISECONDS)
.build())
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With