I've created simple test app to run multiple CoroutineWorkers in the background:
class Work(context: Context, workerParameters: WorkerParameters) :
CoroutineWorker(context, workerParameters) {
override suspend fun doWork(): Result {
Log.d("bagins", "Work ${this.tags.first()} started")
runBlocking {
delay(5000)
}
Log.d("bagins", "Work ${this.tags.first()} finished")
return Result.success()
}
}
I launch them with
workManager.enqueue(workers)
But I don't want all of them to working simultaneously. I want max 2 to be executed at the same time.
Based on examples found I udpated AndroidManifest.xml by adding:
<provider
android:name="androidx.startup.InitializationProvider"
android:authorities="${applicationId}.androidx-startup"
tools:node="remove">
</provider>
And Application class to this:
class App : Application(), Configuration.Provider {
override fun getWorkManagerConfiguration(): Configuration {
val executor = Executors.newFixedThreadPool(2)
return Configuration.Builder().setExecutor(executor).build()
}
override fun onCreate() {
super.onCreate()
WorkManager.initialize(this, workManagerConfiguration)
}
}
If I execute workManager.enqueue multiple (10) times it is executing the CoroutineWorkers simultaneously. I want them to be executed max 2 parallel, and if new added to the queue, I want this rule to still work.
To achieve your goal, you can use a Semaphore, like
Another example:
Both examples were taken from here, I strongly recommend reading the article.