Android的WorkManager的同时作业数/最大值

WorkManager是否对同时运行的作业数量设置上限?

很简单的例子:

>单击按钮,创建10个一次性作业
>将它们全部排队
>一次运行3个作业,而不是按预期运行10个作业

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

最佳答案 可以同时运行的作业数实际上由您配置的线程池确定.默认的Executor定义为
here.

通常,当您使用Worker基类时,您将Worker的实例与此Executor上的线程相关联.如果您希望更好地控制与Worker关联的线程,您可能需要查看CoroutineWorker或ListenableWorker.

默认执行程序中的线程数由设备上的核心数决定.如果您希望同时运行所有10个作业,则必须执行以下操作:

>禁用默认的WorkManager初始值设定项(通过禁用内容提供程序的清单合并).
>在Application.onCreate()或您自己的ContentProvider上初始化WorkManager.您需要在此处执行此操作,因为操作系统可以要求先前安排的工作人员运行.有关更多信息,请查看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个Worker).现在,当您将您的工人入队时,您将看到所有这些工人同时执行.

点赞