2

I need to call some function after x seconds elapsed exactly.

How would I do this in Kotlin?

I've tried with using :

GlobalScope.launch 
{
  val seconds = 5
  val duration = (seconds * 1000).toLong()
  delay(duration)
  callTheFunction ()
}

but based on my measurements looks like it's sometimes accurate and sometimes not. Am I using it in the wrong way or is there a better way to do it?

daneejela
  • 13,081
  • 7
  • 38
  • 50
  • You won't be able to get it at exact intervals. How much error do you want to allow? If the function is long running, you could time how long it takes to run, then subtract that amount from the delay amount. You're still at the mercy of what's going on in your system at the time though. – Carcigenicate Jul 29 '19 at 18:11
  • @Carcigenicate I don't need it to be milliseconds accurate. A second of tolerance is ok, but not 5,10, or some random number of seconds. Is it possible? – daneejela Jul 29 '19 at 18:15
  • Try this [implementation](https://stackoverflow.com/a/43348715/8043806) and put it inside a recursive function call. – Giddy Naya Jul 29 '19 at 18:15
  • Did you consider [JobScheduler](https://developer.android.com/reference/android/app/job/JobScheduler)? [You can specify the required precision](https://developer.android.com/reference/android/app/job/JobInfo.Builder.html#setPeriodic(long,%20long)) and [query the best offered precision](https://developer.android.com/reference/android/app/job/JobInfo.html#getMinFlexMillis()). – MarkusM Jul 29 '19 at 20:10
  • How do you know it takes 5 to 10 seconds? – tynn Jul 30 '19 at 08:44
  • @GiddyNaya if you put it in the answer with a short explanation I can accept it as an answer – daneejela Jul 30 '19 at 09:04

0 Answers0