Using WorkManager in Android to schedule periodic work with PeriodicWorkRequest | Part 1. Getting started
Published: 2023-08-10 21:55:53

### Table of contents
1. [What we are doing](#what)
2. [What type of work are you doing ?](#work)
3. [The 3 step process](#three)
4. [Define the work](#define)
5. [Create a WorkRequest](#request)
6. [Submit the WorkRequest](#submit)
7. [Resources](#resources)


### The code
- [GitHub](https://github.com/thePlebDev/Clicker)

### Introduction <a name="intro"></a>
- I have embarked on my next app, a Twitch client app. This series will be all my notes and problems faced when creating this app.

- This tutorial will be about how to get the WorkManager up and running. The more complicated task of making a API request periodically will be in the next tutorial.


### What we are doing? <a name="what"></a>
- So according to the [Twitch API](https://dev.twitch.tv/docs/authentication/validate-tokens/) we need to validate our OAuthToken on an hourly basis. As it turns out, the best way to do that is with the Android WorkManager

### What type of work are you doing ? <a name="work"></a>
- When dealing with the background work, we first have to ask ourselves. What sort of work are we doing? We have 3 possible options

**1) Immediate :** Tasks that must begin immediately and complete soon. May be expedited

**2) Long Running :** Tasks which might run for longer, potentially longer than 10 minutes.

**3) Deferrable :**  Scheduled tasks that start at a later time and can run periodically. (What we are talking about)

- If you are unsure about what type of work your application uses, please check out the [Documentation](https://developer.android.com/guide/background)

### The 3 step process <a name="three"></a>
- If your work requires the WorkManager, using it can be broken down into a 3 step process:

**1) Define the work:**

**2) Create a WorkRequest :**

**3) Submit the WorkRequest:**  


### 1) Define the work <a name="define"></a>
- As the [documentation](https://developer.android.com/guide/background/persistent/getting-started#define_the_work) states, 

Work is defined using the [Worker](https://developer.android.com/reference/androidx/work/Worker) class. The doWork() method runs asynchronously on a background thread provided by WorkManager.

- So all we have to do is to define a new class, implement the abstract Worker class and override the `doWork()` method. Just like this:
```
class OAuthTokeValidationWorker(
    appContext: Context,
    workerParams: WorkerParameters,
):Worker(appContext,workerParams){
    override fun doWork(): Result {
        Log.d("OAuthTokeValidationWorker","IT IS RUNNING")
        return Result.success()
    }

}

```
- I would like to point out in the code above, that the `Result.success()` is coming from `androidx.work.ListenableWorker.Result` class.


### 2) Create a WorkRequest <a name="request"></a>
- We can again look to the [documentation](https://developer.android.com/guide/background/persistent/getting-started#create_a_workrequest) and read:

 `Once your work is defined, it must be scheduled with the WorkManager service in order to run.`
- For simplicities sake, we are only going to schedule this code to run once. The more complicated once per hour call will be in the next tutorial. So, creating the WorkRequest will look like this:

```
val workRequest = OneTimeWorkRequestBuilder<OAuthTokeValidationWorker>().build()

```

### 3) Submit the WorkRequest <a name="submit"></a>
- Lastly we can use Hilt to inject the application context into a class and use it to get an instance of `WorkManager`
```
class TokenDataStore @Inject constructor(
    private val context:Context
    ){
    init{
         val workManager = WorkManager.getInstance(context)
        val workRequest = OneTimeWorkRequestBuilder<OAuthTokeValidationWorker>().build()
        workManager.enqueue(workRequest)


    }
}

```

### What is next ? <a name="next"></a>
- The next part in this tutorial will be exploring `@HiltWorker ` and showing how we use `WorkManager` to make a api request.


### Resources <a name="resources"></a>
[Getting started with WorkManager](https://developer.android.com/guide/background/persistent/getting-started)
[Worker documentation](https://developer.android.com/reference/androidx/work/Worker)
[Background work](https://developer.android.com/guide/background)



### Conclusion
- Thank you for taking the time out of your day to read this blog post of mine. If you have any questions or concerns please comment below or reach out to me on [Twitter](https://twitter.com/AndroidTristan).