Home > Software design >  What is the best way to schedule a brief task from an already running background service?
What is the best way to schedule a brief task from an already running background service?

Time:09-13

I have implemented a NotificationListenerService that runs in the background.

From this services onNotificationPosted method, I would like to be able to queue work to happen in 2 minutes time.

What is the best way to go about this?

Both JobScheduler and Workmanager have a minimum interval of 15 minutes. Because I already have a background service running, I don't think I really need to use those, correct?

Could I just use something like a TimerTask, or even a sleep in my onNotificationPosted method?

CodePudding user response:

WorkManager has 15 minutes interval only for periodic tasks, thats is not what you want, as I can see. You can schedule task with OneTimeWorkRequest to let it be executed in 2 minutes after the onNotificationPosted method call.

As you already have running service, you can probably just delay your task in separate coroutine scope

launch {
    delay(2 * 60 * 1000)
    yourTask()
}

or use

handler.postDelayed(2 * 60 * 1000) {
    yourTask()
}
  • Related