Scheduling Tasks with WorkManager - Androhub

Scheduling Tasks with WorkManager

In this article, we will learn how to schedule tasks using WorkManager.

What is WorkManager?

WorkManager is a part of Jetpack Components which provides the facility to execute or perform background operations seamlessly.

Benefits of WorkManager:

  1. WorkManager executes works on the background thread which eliminates the creation of threads. But still, you can create a thread inside the worker.
  2. WorkManager comes with constraints that help us to decide that our job never fails and executes successfully.
  3. WorkManager helps us to persist the work means if your device reboots then it will automatically reschedule the pending jobs.

Type of Work Requests

  1. One-Time: For simple jobs that should run one-time. In that case, this request will be used. For example, saving some files in the background.
  2. Periodic: This will be used when you have a job that should execute after some interval (hourly, daily, weekly, etc). For example, sending captured logs to the server daily, taking backups, etc.

VIDEO TUTORIAL

Example

  1. Create a sample project. I am using Compose but you can use XML also.
  2. First, we have to add the following dependency to the level build.gradle file and sync the project.
  3. Now create a worker class named MyWorker.kt and put the following code into it.

    This class contains the following:
    a. Extend the class with the Worker class which tells the current class is a worker.
    b. Creating and executing One-Time and Periodic work requests inside the companion object block.


      c. Adding constraints to work requests.

      d. Passing data using InputData

      e. Cancelling the work.
  4. Now open MainActivity.kt and let’s create ui to start the worker and cancel the worker.

    Full code of MainActivity
  5.  To observe the work states you can use the following function which you can find in the above activity:

    There are six states of work:
    a. Enqueue: When the work is not yet started and in queue.
    b. Running: When the work has started and is in progress.
    c. Success: When the work has been completed successfully.
    d. Failed: When the work has failed due to some exceptions or reasons.
    e. Cancelled: When the work has been canceled.
    f. Blocked: When the work has been blocked from internal consequences.
  6. For creating notifications you can read this article.
  7. Finally, you can download the code and run it. You can watch the tutorial video for the detailed explanation.

Happy Coding :)




Post comment

Your email address will not be published. Required fields are marked *