Timers in Karel
Our first example demonstrates how to work with timers in Java. We’ll explore how to schedule tasks to be executed at a future time or repeatedly at intervals.
import java.util.Timer;
import java.util.TimerTask;
public class TimersExample {
public static void main(String[] args) {
// Timers represent a single event in the future. You
// tell the timer how long you want to wait, and it
// provides a way to be notified 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);
// Wait for the timer to complete
try {
Thread.sleep(2500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 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.
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Clean up the timers
timer1.cancel();
timer2.cancel();
}
}
The first timer will fire ~2 seconds after we start the program, but the second should be stopped before it has a chance to fire.
To run the program, compile and execute it:
$ javac TimersExample.java
$ java TimersExample
Timer 1 fired
Timer 2 stopped
In this Java example, we use the java.util.Timer
and java.util.TimerTask
classes to achieve similar functionality to Go’s timers. The Timer
class is used to schedule tasks (represented by TimerTask
objects) for future execution.
We create two timers:
- The first timer is scheduled to run after 2 seconds and simply prints a message.
- The second timer is scheduled to run after 1 second, but we cancel it immediately after scheduling.
We use Thread.sleep()
to pause the main thread, allowing time for the timers to potentially fire. This is equivalent to the time.Sleep()
function in the original example.
Note that in Java, we need to explicitly clean up the timers by calling cancel()
on them when we’re done. This is not necessary in Go due to its garbage collection mechanism.