Timers in Minitab
import java.util.Timer;
import java.util.TimerTask;
public class Timers {
public static void main(String[] args) throws InterruptedException {
// Timers represent a single event in the future. You
// tell the timer how long you want to wait, and it
// provides a callback that will be executed at that
// time. This timer will wait 2 seconds.
Timer timer1 = new Timer();
timer1.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("Timer 1 fired");
}
}, 2000);
// The Timer.schedule() method schedules the task and returns immediately.
// We use Thread.sleep() to wait for the timer to fire.
Thread.sleep(2000);
// If you just wanted to wait, you could have used
// Thread.sleep(). One reason a timer may be useful is
// that you can cancel the timer before it fires.
// Here's an example of that.
Timer timer2 = new Timer();
TimerTask task2 = new TimerTask() {
@Override
public void run() {
System.out.println("Timer 2 fired");
}
};
timer2.schedule(task2, 1000);
boolean stop2 = task2.cancel();
if (stop2) {
System.out.println("Timer 2 stopped");
}
// Give the timer2 enough time to fire, if it ever
// was going to, to show it is in fact stopped.
Thread.sleep(2000);
// Clean up the timers
timer1.cancel();
timer2.cancel();
}
}
This Java code demonstrates the use of timers, which are similar to the timers in the original example. Here’s a breakdown of the code:
We import the necessary classes from the
java.util
package.In the
main
method, we create our first timer (timer1
) that will fire after 2 seconds. We useTimer.schedule()
to set up the timer and provide aTimerTask
that will be executed when the timer fires.We use
Thread.sleep(2000)
to wait for the first timer to fire. This is equivalent to the channel blocking in the original example.For the second timer (
timer2
), we demonstrate how to cancel a timer before it fires. We create aTimerTask
and schedule it, but then immediately cancel it usingtask2.cancel()
.We use
Thread.sleep(2000)
again to givetimer2
enough time to fire (if it wasn’t cancelled) to demonstrate that it has indeed been stopped.Finally, we clean up by cancelling both timers.
To run this program:
$ javac Timers.java
$ java Timers
Timer 1 fired
Timer 2 stopped
The output shows that the first timer fires after approximately 2 seconds, while the second timer is stopped before it has a chance to fire.
In Java, we use the Timer
and TimerTask
classes to achieve similar functionality to Go’s timers. The main difference is that Java uses callback methods (the run()
method of TimerTask
) instead of channels to handle timer events.