Scheduling Tasks with Work a Manager
Learn how to schedule tasks using work managers.
We'll cover the following...
We'll cover the following...
Introduction
Work managers provide APIs that let us schedule background tasks. They provide easy-to-use APIs and fine-grained controls on task execution, as well as robust scheduling APIs with retrial and chaining for complex tasks.
Let’s learn how to schedule tasks using work managers.
Schedule tasks with a delay
We can use work managers to schedule a task after a specified time duration. First, we define a class for our task by extending the Worker
class. For example, let’s create a task to generate a random number less than 1100 and return success if the number is less than 750.
Press + to interact
import android.content.Contextimport androidx.work.Dataimport androidx.work.Workerimport androidx.work.WorkerParametersimport androidx.work.workDataOfimport java.util.*class GenerateRandomNumberWorker(appContext: Context, workerParams: WorkerParameters) :Worker(appContext, workerParams) {override fun doWork(): Result {val r = Random()val nextNum = r.nextInt(1100)return when {nextNum <= 750 -> {val output: Data = workDataOf("randomNumber" to nextNum)Result.success(output)}else -> {Result.failure()}}}}
Note: Refer to the ...