Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve multiple instance issue on a work manager?

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.

like image 690
Arafat Avatar asked Oct 14 '18 06:10

Arafat


People also ask

How do I stop WorkManager?

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.

What is Flex interval in work manager?

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.

How do you pass parameters to WorkManager?

public static OneTimeWorkRequest create(String id) { Data inputData = new Data. Builder() . putString(TASK_ID, id) . build(); return new OneTimeWorkRequest.

When would you use a WorkManager?

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.


1 Answers

You can use the fun WorkManager.enqueueUniquePeriodicWork

This function needs 3 params:

  1. tag (string) so it would look for other previously created work requests with this tag
  2. strategy to use when finding other previously created work requests. You can either replace the previous work or keep it
  3. your new work 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())

}
like image 99
Re'em Avatar answered Sep 22 '22 02:09

Re'em