Search code examples
androidkotlinandroid-workmanager

Kotlin Workmanager strange execution times


I created my first "PeriodicWorkManager". I want it to run on every hour. (Best would be at minute 0 of hour). So I created a Workmanager like this:

WorkManager.getInstance(this).cancelAllWorkByTag("DrinkNotify")
        val work2 = PeriodicWorkRequest.Builder(NotifyWorker::class.java, 1, TimeUnit.HOURS)
            .setConstraints(Constraints.NONE)
            .addTag("DrinkNotify")
            .build()
        WorkManager.getInstance(this).enqueue(work2)

NotifyWorker class looks like this:

class NotifyWorker(appContext: Context, workerParams: WorkerParameters):Worker(appContext, workerParams) {
    var appContext = appContext
    override fun doWork(): Result {
        if(this.tags.contains("DrinkNotify")){
            Log.d("CUSTOM","WURDE AUSGEFÜHRT")
        }
        return Result.retry()
    }
}

I started the WorkManager and saw the initial function running (which is okay for me) but instead of running every hour after initialising it runs like this:

2021-02-03 20:38:31.995 22945-22973/com.workmanagerdemo D/CUSTOM: WURDE AUSGEFÜHRT

2021-02-03 20:39:32.108 22945-22990/com.workmanagerdemo D/CUSTOM: WURDE AUSGEFÜHRT

2021-02-03 20:41:32.213 22945-23006/com.workmanagerdemo D/CUSTOM: WURDE AUSGEFÜHRT

2021-02-03 20:45:32.304 22945-22973/com.workmanagerdemo D/CUSTOM: WURDE AUSGEFÜHRT

2021-02-03 20:54:34.114 22945-22990/com.workmanagerdemo D/CUSTOM: WURDE AUSGEFÜHRT

So at first it gets executed 1 minute after the initial, then its 2 minutes, 4 minutes and 9 minutes.

I don't get why it's running like this. Do you have an idea?

Thanks in advance!


Solution

  • WorkManager does not guarantee to execute your work at a particular time. For the above scenario, you can use AlarmManager with WorkManager.

    WorkManager will start your work once the constraints are fulfilled and AlarmManager will execute it after every hour.

    Here, is a project which contains the code for it but it does not fulfill all your requirement. You can play with it and you will get to know how it can be executed.

    GitHub Project