Search

Dark theme | Light theme

November 14, 2009

Groovy Goodness: Run Code at a Specified Time

In Groovy we can use the method runAfter() to run a closure after a specified delay in milliseconds. This method is added by Groovy GDK to the Timer class.

// File: timer.groovy
def timer = new Timer()
def task = timer.runAfter(10000) {
    println "Actually executed at ${new Date()}."
}
println "Current date is ${new Date()}. Task is executed at ${new Date(task.scheduledExecutionTime())}."

If we run this script we get the following output (of course depending on the time the script is executed):

$ groovy timer.groovy
Current date is Thu Nov 12 6:51:41 CET 2009. Task is executed at Thu Nov 12 6:51:51 CET 2009.
Actually executed at Thu Nov 12 6:51:51 CET 2009.

As a bonus we add a runEvery() method to the Timer class with categories:

// File: newtimer.groovy
class GroovyTimerTask extends TimerTask {
    Closure closure
    void run() {
        closure()
    }
}

class TimerMethods {
    static TimerTask runEvery(Timer timer, long delay, long period, Closure codeToRun) {
        TimerTask task = new GroovyTimerTask(closure: codeToRun)
        timer.schedule task, delay, period
        task
    }
}

use (TimerMethods) {
    def timer = new Timer()
    def task = timer.runEvery(1000, 5000) {
        println "Task executed at ${new Date()}."
    }
    println "Current date is ${new Date()}."
}
$ groovy newtimer.groovy
Current date is Thu Nov 12 7:03:29 CET 2009.
Task executed at Thu Nov 12 7:03:30 CET 2009.
Task executed at Thu Nov 12 7:03:35 CET 2009.
Task executed at Thu Nov 12 7:03:40 CET 2009.
Task executed at Thu Nov 12 7:03:45 CET 2009.
Task executed at Thu Nov 12 7:03:50 CET 2009.
...