When we use Timer and TimerTask, we are enforcing that each iteration is started at a proper interval, regardless of the time it takes to execute. Keep in mind that if the execution time is longer than the interval, the code will be executed twice in parallel and race conditions may appear.
Let's see how to blink an LED using Timer and TimerTask:
class BlinkTimerActivity : Activity() {
private lateinit var led: Gpio
private val timer = Timer()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
led = RainbowHat.openLedGreen()
timer.schedule ( timerTask {
led.value = !led.value
}, 0, 1000 )
}
override fun onDestroy() {
super.onDestroy()
timer.cancel()
timer.purge()
led.close()
}
}
In this example, we create a timer value of type Timer and we schedule a TimerTask to be executed every 1,000 milliseconds. The code of the task is simply to toggle the LED.
Then, as part of onDestroy, we cancel and purge the timer, to stop the rescheduling and to remove any scheduled tasks.
In this case we guarantee that the call will start every second. Take a look at the following diagram to see the difference between a handler and a timer: