Timer() fixedRateTimer 设置为 20 秒不会在触发 onStop 时停止
Timer() fixedRateTimer set for 20 sec does not stop when onStop is triggered
我有一个计时器设置为在 activity 处于活动状态时每 20 秒记录一次时间戳。
它正确地记录了时间,但是当我的 Activity 的 onStop 方法被触发时,它继续到 运行。我已确认触发了 onStop,但计时器会一直持续下去。这是我的 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")
}
}
}
}
这是我的协程扩展,以防万一:
object Coroutines{
fun io(work: suspend (() -> Unit)) =
CoroutineScope(Dispatchers.IO).launch {
work()
}
}
谁能帮我弄清楚如何正确停止这个计时器?
您正在通过两次 checkForUpdates()
调用创建两个 Timer
对象,并且您只取消了第二个。也许去掉 onStop()
中的 checkForUpdates()
调用。
我有一个计时器设置为在 activity 处于活动状态时每 20 秒记录一次时间戳。 它正确地记录了时间,但是当我的 Activity 的 onStop 方法被触发时,它继续到 运行。我已确认触发了 onStop,但计时器会一直持续下去。这是我的 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")
}
}
}
}
这是我的协程扩展,以防万一:
object Coroutines{
fun io(work: suspend (() -> Unit)) =
CoroutineScope(Dispatchers.IO).launch {
work()
}
}
谁能帮我弄清楚如何正确停止这个计时器?
您正在通过两次 checkForUpdates()
调用创建两个 Timer
对象,并且您只取消了第二个。也许去掉 onStop()
中的 checkForUpdates()
调用。