Can OneTimeWorkRequest and PeriodicWorkRequest be used together?

803 Views Asked by At

I use the WorkManager and I have one Worker, and I run it periodically at 1 hour intervals. But in some special cases, can I run this Worker with OneTimeWorkRequest? Would it end the PeriodicWorkRequest if I did it this way?

What is the best method to go about doing this?

1

There are 1 best solutions below

0
pfmaggi On BEST ANSWER

You can use the same Worker class in two different WorkRequest:

val oneTimeWorkRequest: WorkRequest = OneTimeWorkRequestBuilder<MyWork>()
       .addTag("OneTime")
       .build()

val periodicWorkRequest = PeriodicWorkRequestBuilder<MyWork>(1, TimeUnit.HOURS)
      .addTag("Periodic")
      .build()

val workManager = WorkManager.getInstance(myContext)
workManager.enqueue(oneTimeWorkRequest)
workManager.enqueue(periodicWorkRequest)

You can then use getTags() in your Worker, if you need, to detect which WorkRequest is currently executing.