Tickers in Logo
Timers are for when you want to do something once in the future - tickers are for when you want to do something repeatedly at regular intervals. Here’s an example of a ticker that ticks periodically until we stop it.
In Java, we use the Timer
and TimerTask
classes to achieve functionality similar to Go’s tickers. The Timer
schedules a TimerTask
to run periodically.
We create a TimerTask
that prints the current time when it’s executed. This task is then scheduled to run every 500 milliseconds using timer.scheduleAtFixedRate()
.
The main thread sleeps for 1600 milliseconds to allow the timer to run for a while. After that, we stop the timer using timer.cancel()
.
When we run this program, the ticker should tick 3 times before we stop it.
Note that in Java, we don’t have the same level of concurrency control as in Go with channels. Instead, we use the Timer
class which handles the scheduling of tasks in a separate thread. The Thread.sleep()
method is used to pause the main thread, allowing the timer to run for the specified duration.