Timers in Fortress

import java.util.Timer;
import java.util.TimerTask;

public class Timers {
    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 execute a task 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);

        // We use Thread.sleep to block the main thread until the timer fires.
        try {
            Thread.sleep(2000);
        } 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();
    }
}

We often want to execute Java code at some point in the future, or repeatedly at some interval. Java’s Timer and TimerTask classes make both of these tasks easy.

In this example, we create two timers. The first timer is set to fire after 2 seconds, and when it does, it prints “Timer 1 fired”. We use Thread.sleep() to block the main thread until the timer fires.

The second timer is set to fire after 1 second, but we cancel it before it has a chance to fire. This demonstrates how you can cancel a timer if you no longer need it.

To run the program, compile and execute it:

$ javac Timers.java
$ java Timers
Timer 1 fired
Timer 2 stopped

The first timer will fire ~2s after we start the program, but the second should be stopped before it has a chance to fire.

Note that in Java, we use Timer and TimerTask classes instead of channels. Also, we need to explicitly cancel the timers at the end to clean up resources, which is not necessary in some other languages with automatic resource management.

Java’s concurrency utilities provide more advanced timing mechanisms, such as ScheduledExecutorService, which might be more appropriate for complex scenarios or when working with thread pools.