I have Google it, whereas all answers i got simplely check only one shceduled task is finished. What i want is to check whether all tasks are finished or is timer is idle? Is there a good way to manage do it?
val timer =Timer()
timer.schedule(object:TimerTask(){
override fun run() {
Timber.d("task1")
}
},1000)
timer.schedule(object:TimerTask(){
override fun run() {
Timber.d("task2")
}
},3000)
IIRC there is no built-in functions to check for timer if it has finished all tasks.
One thing you can do is to create an extension function that may count for that.
fun Timer.schedule(delay: Long, counter: AtomicInteger, task: TimerTask.() -> Unit) {
counter.incrementAndGet()
schedule(object : TimerTask{
override fun run() {
task()
counter.decrementAndGet()
}
}, delay)
}
Now call the schedule by passing a AtomicInteger.
val timer = Timer()
val counter = AtomicInteger(0)
timer.schedule(1_000L, counter) {
Timber.d("task1")
}
timer.schedule(3_000L, counter) {
Timber.d("task2")
}
// check somewhere
val remaining = counter.get()
if (remaining == 0) {
// timer has finished all the tasks
} else {
// timer has tasks remaining
println("Timer has $remaining tasks")
}
However the major drawback of this synthetic sugar is that if you use the actual Timer.schedule
defined in the class, then you have no way of determining how much tasks are alive. Because std-lib does not implement the functionality anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With