Timers in Julia

Julia provides built-in timing features that make it easy to execute code at some point in the future or repeatedly at some interval. We’ll look at timers in this example.

using Dates

function main()
    # Timers represent a single event in the future. You
    # tell the timer how long you want to wait, and it
    # will execute a function after that time. This timer
    # will wait 2 seconds.
    timer1 = Timer(2) do _
        println("Timer 1 fired")
    end

    # The `wait` function blocks until the timer fires
    wait(timer1)

    # If you just wanted to wait, you could have used
    # `sleep`. One reason a timer may be useful is
    # that you can cancel the timer before it fires.
    # Here's an example of that.
    timer2 = Timer(1) do _
        println("Timer 2 fired")
    end

    # Attempt to stop the timer
    close(timer2)
    println("Timer 2 stopped")

    # Give timer2 enough time to fire, if it ever
    # was going to, to show it is in fact stopped.
    sleep(2)
end

main()

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

$ julia timers.jl
Timer 1 fired
Timer 2 stopped

In this Julia version:

  1. We use the Timer constructor to create timers. The first argument is the delay in seconds, and the second is a function to execute when the timer fires.

  2. Instead of channels, Julia’s Timer executes a given function when it fires.

  3. The wait function is used to block until a timer fires.

  4. To stop a timer in Julia, we use the close function.

  5. Julia’s sleep function is used for simple delays, similar to Go’s time.Sleep.

Note that Julia’s timing functions are generally more precise than Go’s, often operating at nanosecond resolution.