I want to run “lastTask” 3 seconds after the last time a function “cTG” is called. Here is an example:
public fun cTG(counter: Int) {
// do some things here
Timer("lastTask").cancel()
Timer("lastTask", false).schedule(3000)
{
lastTask(counter)
}
}
The code runs, but it doesn’t seem to be cancelling the previously scheduled “lastTask”. In other words, I have a whole bunch of "lastTask"s showing up instead of just one.
Hello,
In pasted code, you create a new Timer each time you cal cTG method. In fact, the name passed at built is not a unique identifier used by the system to find previously used tasks, but simply a label to help debug.
You should reuse the same Timer instance if you want control over scheduled tasks. Anyway, a Timer instance is costly because according to javadoc, each instance pops its own thread.
To cancel a task, you have to get the TimerTask returned by schedule method, then call cancel on this object.
For further details, I redirect you to:
- Java Timer api doc regarding Timer usage and acquisition: Timer (Java Platform SE 8 )
- Kotlin extension over Timer, for schedule method: java.util.Timer - Kotlin Programming Language