WorkManager是否限制同时运行的作业数量?
非常简单的示例:
class MainActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
queue.setOnClickListener {
val jobs = mutableListOf<OneTimeWorkRequest>()
for( i in 1..10 ) {
jobs += OneTimeWorkRequestBuilder<MyWorker>()
.setInputData(workDataOf("key" to i))
.build()
}
WorkManager.getInstance().enqueue(jobs)
}
}
}
class MyWorker: Worker() {
override fun doWork(): Result {
val jobId = inputData.getInt("key", -1)
Log.d("worker", "starting job: $jobId")
Completable.timer(10, SECONDS).blockingGet()
Log.d("worker", "job finished: $jobId")
return SUCCESS
}
}
输出:
08-30 14:03:10.392 9825 9855 D worker : starting job: 2
08-30 14:03:10.396 9825 9856 D worker : starting job: 3
08-30 14:03:10.400 9825 9854 D worker : starting job: 1
08-30 14:03:20.421 9825 9855 D worker : job finished: 2
08-30 14:03:20.421 9825 9856 D worker : job finished: 3
08-30 14:03:20.421 9825 9854 D worker : job finished: 1
08-30 14:03:20.442 9825 9856 D worker : starting job: 4
08-30 14:03:20.448 9825 9854 D worker : starting job: 5
08-30 14:03:20.450 9825 9855 D worker : starting job: 6
08-30 14:03:30.444 9825 9856 D worker : job finished: 4
08-30 14:03:30.449 9825 9854 D worker : job finished: 5
08-30 14:03:30.451 9825 9855 D worker : job finished: 6
08-30 14:03:30.474 9825 9856 D worker : starting job: 7
08-30 14:03:30.477 9825 9855 D worker : starting job: 8
08-30 14:03:30.480 9825 9854 D worker : starting job: 9
08-30 14:03:40.476 9825 9856 D worker : job finished: 7
08-30 14:03:40.478 9825 9855 D worker : job finished: 8
08-30 14:03:40.481 9825 9854 D worker : job finished: 9
08-30 14:03:40.497 9825 9856 D worker : starting job: 10
08-30 14:03:50.500 9825 9856 D worker : job finished: 10
答案 0 :(得分:3)
可以同时运行的作业数实际上由您配置的线程池确定。默认的Executor
定义为here。
通常,当您使用Worker
基类时,会将Worker
的实例与该Executor
上的线程相关联。如果您想更好地控制Worker
与哪个线程相关联,则可以查看一下CoroutineWorker
或ListenableWorker
。
默认Executor
中的线程数由设备上的内核数决定。如果要同时运行所有10个作业,则必须执行以下操作:
禁用默认的WorkManager
初始化程序(通过为内容提供程序禁用清单合并)。
在WorkManager
或您自己的Application.onCreate()
上初始化ContentProvider
。您需要在此处执行此操作,因为操作系统可以要求先前安排的Worker
运行。有关更多信息,请查看this。
val configuration = Configuration.Builder()
// Defines a thread pool with 10 threads.
// Ideally you would choose a number that is dynamic based on the number
// of cores on the device.
.setExecutor(Executors.newFixedThreadPool(10))
.build()
WorkManager.initialize(context, configuration)
在上面的示例中,我创建了一个具有10个线程的固定大小的线程池(该线程池又可以处理10个Workers
)。现在,当您将Worker
排入队列时,您将看到它们全部同时执行。