Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine whether my Timer has finished all tasks?

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)
like image 249
Cyrus Avatar asked Sep 14 '25 18:09

Cyrus


1 Answers

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.

like image 195
Animesh Sahu Avatar answered Sep 17 '25 08:09

Animesh Sahu