The App may sometimes need to run certain tasks on a regular basis. For example, you might periodically back up data, upload information to the server, periodically fetch new content, and so on. During the app run, we can also use Handler to complete regular functions. Here we describe how WorkManager uses scheduled tasks.

Earlier we looked at WorkManager usage, constraints, and latency. This article describes the scheduled tasks of WorkManager. This section describes how to create a scheduled task, view the task status, and cancel the task.

This article uses Kotlin

Note: The minimum repetition interval that can be defined is 15 minutes (same as the JobScheduler API).

gradle

When using PeriodicWorkRequestBuilder kotlin report errors

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6. Please specify proper ‘-jvm-target’ option

Add jvmTarget for kotlinOptions to app Gradle configuration as prompted

android {
    // Other configuration...

    kotlinOptions {
        jvmTarget = "1.8"}}Copy the code

Creating a Scheduled Task

Create tasks regularly, use PeriodicWorkRequestBuilder, incoming timing parameters, the build () to get a task instance. The enqueue method to the WorkManager.

val r1 = PeriodicWorkRequestBuilder<UploadWorker2>(15, TimeUnit.MINUTES)
        .addTag("r1").build()
WorkManager.getInstance(applicationContext).enqueue(r1)
Copy the code

The above code will execute a task immediately after enqueue. You can create multiple scheduled tasks by creating multiple tasks.

Note: The minimum repetition interval that can be defined is 15 minutes (same as the JobScheduler API).

A single task

If you don’t want to repeat the timing task, need to use the WorkManager enqueueUniquePeriodicWork method.

val r1 = PeriodicWorkRequestBuilder<UploadWorker2>(15, TimeUnit.MINUTES)
        .addTag("r2").build()
WorkManager.getInstance(applicationContext)
        .enqueueUniquePeriodicWork(
                "Single scheduled task R2.",
                ExistingPeriodicWorkPolicy.KEEP,
                r1)
Copy the code

After using PeriodicWorkRequestBuilder create task. Call enqueueUniquePeriodicWork, this method requires three parameters:

  • uniqueWorkNameUnique mission name
  • ExistingPeriodicWorkPolicyWhat to do if a task is found to be duplicated
    • REPLACEStop and delete the old task, and then insert the new task
    • KEEPKeep the original task and do not add it
  • PeriodicWorkRequestThe task object

EnqueueUniquePeriodicWork method can ensure that a name is only a regular tasks at the same time (PeriodicWorkRequest). If it is the same name (uniqueWorkName), inserting a task may either REPLACE the old task (REPLACE) or leave the old task (KEEP) unaffected.

View the task

Here we use getWorkInfosByTag to query the task

val status = WorkManager.getInstance(applicationContext).getWorkInfosByTag("r1")
val workInfoList: List<WorkInfo> = status.get(a)for (w in workInfoList) {
    Log.d("rustfisher.com"." $w")}Copy the code

Examples of query results

 WorkInfo{mId='83d7d512-8a5d-4613-acbb-e73ee2855212', mState=ENQUEUED, mOutputData=Data {}, mTags=[com.rustfisher.tutorial2020.workmanaer.WorkManagerAct$UploadWorker2, r1], mProgress=Data {}}
Copy the code

Cancel the task

We have a number of ways to cancel the mission.

Cancel all tasks

CancelAllWork (), cancels all tasks

WorkManager.getInstance(applicationContext).cancelAllWork()
Copy the code

Cancel individual tasks

CancelUniqueWork (uniqueWorkName: String), cancels the individual task and passes in uniqueWorkName

WorkManager.getInstance(applicationContext).cancelUniqueWork("Single scheduled task R2.")
Copy the code

Cancel all tasks that pass in a tag

CancelAllWorkByTag (tag) : cancels all tasks passed with a tag

WorkManager.getInstance(applicationContext).cancelAllWorkByTag("r1")
Copy the code

Cancels the task for a specific UUID

CancelWorkById (UUID), cancels the task for a specific UUID

WorkManager.getInstance(applicationContext).cancelWorkById(UUID)
Copy the code

After the task is CANCELLED, mState=CANCELLED

WorkInfo{mId='7c9e0deb-5267-4ade-8b95-c695e57f274c', mState=CANCELLED, mOutputData=Data {}, mTags=[r2, com.rustfisher.tutorial2020.workmanaer.WorkManagerAct$UploadWorker2], mProgress=Data {}}
Copy the code

reference

  • Introductory WorkManager using an.rustfisher.com/android/jet…
  • The WorkManager work constraints, delay and query work an.rustfisher.com/android/jet…
  • Regular work developer.android.com/topic/libra…
  • Observe work developer.android.com/topic/libra…