Using Timer and Timertask

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.

Timer and TimerTask guarantee that each execution starts at the proper interval.

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 onDestroywe 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:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.246.193