🎯 Objective We will perform a very simple task of printing a number in the logs every 15 minutes with the help of Work Manager. 🤔 What is Work Manager? Work Manager is a simple library for doing any work . Here, a background task which needs to be executed at an moment is considered to be and by I mean that the task should be executed even if the user exits the app or the device restarts. deferrable background reliably doesn't exact deferrable reliably 👨🏽💻 Let's code ⚠️ Pre-requisites Create an android project with an Empty activity. Select Launcher Activity and Generate layout file options. 1. Verify you have in file. If not please add it. The result should look as below : 2. google() Project level build.gradle allprojects { repositories { google() } } // If you're using a version of Gradle lower than 4.1, you must instead use: // maven { // url 'https://maven.google.com' // } // An alternative URL is 'https://dl.google.com/dl/android/maven2/' 👉🏼 Import library In file paste the following the line of code : Module level build.gradle implementation "androidx.work:work-runtime:2.5.0" For latest available version of this library, please refer . this page 👉🏼 Create a Worker class Create a new class and it should extend . 1. MyWorker Worker Create a parameterized constructor : 2. { (context, workerParams); } public MyWorker (@NonNull Context context, @NonNull WorkerParameters workerParams) super Override and implement the method : 3. doWork() { ; } @NonNull @Override Result public doWork () return null Create a new static integer variable called count. 4. Inside the , increase value of count and also print the value in log : 5. doWork() count++; Log.d( , +count+ ); "MyWorker" "worker called - " " time(s)" 💡 is the method where we need to perform the actual background task, this method gets executed on a background thread. It is good for doing tasks. For asynchronous task I will write another tutorial. doWork() Synchronous Return . 6. Result.success() We've written our worker class and the final class should look similar to : { count = ; { (context, workerParams); } { count++; Log.d( , + count + ); Result.success(); } } public class MyWorker extends Worker private static int 0 public MyWorker (@NonNull Context context, @NonNull WorkerParameters workerParams) super @NonNull @Override Result public doWork () "MyWorker" "worker called - " " time(s)" return 👉🏼 Create UI In create a Button inside the : activity_main.xml LinearLayout <?xml version="1.0" encoding="utf-8"?> < = = = = = = = > LinearLayout xmlns:android "http://schemas.android.com/apk/res/android" xmlns:tools "http://schemas.android.com/tools" android:layout_width "match_parent" android:layout_height "match_parent" android:orientation "horizontal" tools:context ".MainActivity" android:layout_margin "16dp" < = = = = = /> Button android:id "@+id/trigger_job" android:layout_width "match_parent" android:layout_height "wrap_content" android:layout_gravity "center" android:text "Trigger Job" </ > LinearLayout 👉🏼 Start worker on button press In , create a Button type variable and map it to xml button using : 1. MainActivity findViewById() Button scheduleJob = findViewById(R.id.trigger_job); Set a new on button : 2. onClickListener() scheduleJob.setOnClickListener( View.OnClickListener() { { } }); new @Override public void onClick (View v) Inside the onClickListener(), assuming that we don't want to run this job when battery is low, create Constraints for the job : 3. Constraints constraints = Constraints.Builder() .setRequiresBatteryNotLow( ) .build(); new true 💡 Constraints as the name implies are set of conditions that must be satisfied for the job to execute. For more details please refer . this link Create a periodic work request, we need to specify our worker class, time and its unit in which our task will be execute at least once as long as the constraints are satisfied. 4. PeriodicWorkRequest periodicWorkRequest = PeriodicWorkRequest.Builder(MyWorker.class, , TimeUnit.MINUTES) .setConstraints(constraints) .build(); new 15 Enqueue this periodic work request. We need to provide a unique name to be used by this worker, whether to replace or keep the pending (uncompleted) request, and object that we have created previously. We'll display a toast on the screen to notify user that work has been scheduled. 5. periodicWorkRequest WorkManager workManager = WorkManager.getInstance(getApplicationContext()); workManager.enqueueUniquePeriodicWork( , ExistingPeriodicWorkPolicy.KEEP,periodicWorkRequest); Toast.makeText(MainActivity. , , Toast.LENGTH_SHORT).show(); "Counter" this "🎉 Scheduled job!" The class will look similar to this : MainActivity { { .onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button scheduleJob = findViewById(R.id.trigger_job); scheduleJob.setOnClickListener( View.OnClickListener() { { Constraints constraints = Constraints.Builder() .setRequiresBatteryNotLow( ) .build(); PeriodicWorkRequest periodicWorkRequest = PeriodicWorkRequest.Builder(MyWorker.class, , TimeUnit.MINUTES) .setConstraints(constraints) .build(); WorkManager workManager = WorkManager.getInstance(getApplicationContext()); workManager.enqueueUniquePeriodicWork( , ExistingPeriodicWorkPolicy.KEEP,periodicWorkRequest); Toast.makeText(MainActivity. , , Toast.LENGTH_LONG).show(); } }); } } public class MainActivity extends AppCompatActivity @Override protected void onCreate (Bundle savedInstanceState) super new @Override public void onClick (View v) new true new 15 "Counter" this "🎉 Scheduled job!" 💻 Let's run the code 🖱 Click the button on the UI : 👀 Observe in the logcat : ⌚ After some time we see : 📴 After a reboot, we again see : 🥳 Good work. Mission Accomplished! 💽 Code can be downloaded from here : github.com/jaikherajani/AndroidWorkerManager Previously published at https://www.jaikherajani.dev/how-to-schedule-a-periodic-background-job-using-work-manager-in-android