本文介绍了CoroutineWorker 可以调度另一个工人吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想与工人安排另一份工作.但是,我在文档中找不到是否允许这样做.

I would like to schedule another job with a worker. But, I couldn't find in the doc if that is allowed or not.

类似于:

class MyWorker(context: Context, params: WorkerParameters): CoroutineWorker(context, params) {

    override val coroutineContext = Dispatchers.IO

    override suspend fun doWork(): Result = coroutineScope {
        val syncWorker = OneTimeWorkRequestBuilder<MyWorker>()
            .setInitialDelay(3000, TimeUnit.MILLISECONDS)
            .build()

        WorkManager.getInstance(context)
            .enqueueUniqueWork("MyJob", ExistingWorkPolicy.REPLACE, syncWorker)
        Result.success()
    }

推荐答案

可以,但有一个例外.

唯一可能危险的情况是,如果您正在使用来自同一工作人员的实例的 ExistingWorkPolicy.REPLACE 将唯一工作人员排队(以您的示例为例,您不能从同一工作人员重新安排工作syncWorker):

The only case that can be dangerous is if you are enqueuing an unique worker with a ExistingWorkPolicy.REPLACE from an instance of the same worker (taking your example, you cannot reschedule the work from the same syncWorker):

class syncWorker(context: Context, params: WorkerParameters): CoroutineWorker(context, params) {

    override suspend fun doWork(): Result {
        withContext(Dispatchers.IO) {
            val syncWorker = OneTimeWorkRequestBuilder<MyWorker>()
                .build()

            // DON'T DO THIS!!!
            // You may end up with two instances of the same worker
            // running at the same time
            WorkManager.getInstance(context)
                .enqueueUniqueWork("MyJob", ExistingWorkPolicy.REPLACE, syncWorker)
            Result.success()
        }
    }
}

还要注意 coroutineContext 现已弃用.改用 withContext(Dispatchers.IO) 就像在我的片段中显示一样.

Also note that coroutineContext is now deprecated. Use instead withContext(Dispatchers.IO) like show in my snippets.

这篇关于CoroutineWorker 可以调度另一个工人吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 10:14