...

/

Scheduling Tasks with Work a Manager

Scheduling Tasks with Work a Manager

Learn how to schedule tasks using work managers.

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.Context
import androidx.work.Data
import androidx.work.Worker
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import 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()
}
}
}
}
...