Timers in Groovy

Our first example demonstrates the use of timers in Groovy. Timers allow us to execute code at a specific point in the future or repeatedly at some interval. We’ll look at timers in this example.

import java.util.concurrent.TimeUnit

class TimerExample {
    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
        // will execute after that time. This timer will wait 2 seconds.
        Timer timer1 = new Timer()
        timer1.schedule(new TimerTask() {
            void run() {
                println "Timer 1 fired"
            }
        }, 2000)

        // Wait for the timer to complete
        TimeUnit.SECONDS.sleep(2)

        // 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() {
            void run() {
                println "Timer 2 fired"
            }
        }
        timer2.schedule(task2, 1000)

        // Cancel the timer before it has a chance to run
        boolean stop2 = task2.cancel()
        if (stop2) {
            println "Timer 2 stopped"
        }

        // Give the timer2 enough time to fire, if it ever
        // was going to, to show it is in fact stopped.
        TimeUnit.SECONDS.sleep(2)

        // Clean up the timers
        timer1.cancel()
        timer2.cancel()
    }
}

To run the program, save it as TimerExample.groovy and use the groovy command:

$ groovy TimerExample.groovy
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.

In this Groovy example, we use the java.util.Timer class to create timers. The schedule method is used to set up a task to run after a specified delay. We use TimerTask to define the actions to be performed when the timer fires.

For the second timer, we demonstrate how to cancel a timer before it fires. The cancel() method returns true if the task was successfully cancelled.

Note that in Groovy, we don’t need to explicitly import classes from java.util as they are automatically imported. However, we do need to import java.util.concurrent.TimeUnit for the sleep functionality.

This example shows how to work with timers in Groovy, which provides a way to schedule tasks for future execution or repeated intervals.