Search code examples
androidandroid-workmanagerworkmanagers

Can OneTimeWorkRequest and PeriodicWorkRequest be used together?


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?


Solution

  • 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.