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.
import java.util.Timer;
import java.util.TimerTask;
public class Tickers {
public static void main(String[] args) {
// Tickers in Java can be implemented using the Timer class
// We'll create a Timer that schedules a task every 500 milliseconds
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Tick at " + new java.util.Date());
}
};
timer.scheduleAtFixedRate(task, 0, 500);
// We'll let the timer run for 1600 milliseconds before stopping it
try {
Thread.sleep(1600);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Stop the timer
timer.cancel();
System.out.println("Timer stopped");
}
}
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.
$ javac Tickers.java
$ java Tickers
Tick at Sun Sep 23 11:29:56 PDT 2012
Tick at Sun Sep 23 11:29:56 PDT 2012
Tick at Sun Sep 23 11:29:57 PDT 2012
Timer stopped
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.