Search code examples
androidkotlintimerkotlin-coroutines

Timer() fixedRateTimer set for 20 sec does not stop when onStop is triggered


I have a Timer set to take a time stamp every 20 seconds when the activity is active. It registers the time correctly, but when my Activity's onStop method is triggered it continues to run. I have confirmation that the onStop is triggered, but the timer continues forever. Here what I have in my Activity:

private lateinit var timer: Timer


override fun onStart() {
    super.onStart()
    checkForUpdates(true)
}

override fun onStop() {
    super.onStop()
    println("super.onStop triggered")
    checkForUpdates(false)
    timer.cancel()
    timer.purge()
}

private fun checkForUpdates(daemonIsTrue: Boolean) {
        timer = fixedRateTimer("default", daemonIsTrue, 0L, 20000) {
            Coroutines.io {
                val dateStamp = DateTime(DateTimeZone.UTC).toString("YYYY-MM-dd HH:mm:ss")
                println("dateStamp at $dateStamp")  
            }
        }
    }
}

Here is my Coroutines extension, just in case:

object Coroutines{
    fun io(work: suspend (() -> Unit)) =
            CoroutineScope(Dispatchers.IO).launch {
                work()
            }
}

Can anybody help me figure out how to properly stop this Timer?


Solution

  • You are creating two Timer objects, via two checkForUpdates() calls, and you are only cancelling the second one. Perhaps get rid of the checkForUpdates() call in onStop().