Tickers in Julia

Our example demonstrates how to use tickers in Julia, which are useful for executing tasks repeatedly at regular intervals. Here’s the code that shows how to create, use, and stop a ticker:

using Dates

function main()
    # Create a channel to receive ticker events
    ticker_channel = Channel{DateTime}(1)

    # Create a channel to signal when to stop
    done = Channel{Bool}(1)

    # Start a task that simulates a ticker
    @async begin
        while true
            if isready(done)
                break
            end
            put!(ticker_channel, now())
            sleep(0.5)  # Sleep for 500 milliseconds
        end
    end

    # Start a task to process ticker events
    @async begin
        while true
            select(
                ticker_channel => t -> println("Tick at ", t),
                done => _ -> break
            )
        end
    end

    # Let the ticker run for 1.6 seconds
    sleep(1.6)

    # Stop the ticker
    put!(done, true)
    println("Ticker stopped")
end

main()

In this example, we use Julia’s Channel type to simulate a ticker. The ticker sends the current time to a channel every 500 milliseconds.

We use two asynchronous tasks: one to simulate the ticker by putting values into the ticker_channel, and another to process these values.

The select statement in Julia allows us to wait for multiple channel operations, similar to its counterpart in other languages. Here, we use it to either process a tick or exit when the done signal is received.

After letting the ticker run for 1.6 seconds, we stop it by sending a signal through the done channel.

When we run this program, the ticker should tick 3 times before we stop it:

$ julia tickers.jl
Tick at 2023-06-01T12:00:00.500
Tick at 2023-06-01T12:00:01.000
Tick at 2023-06-01T12:00:01.500
Ticker stopped

This example demonstrates how to create periodic events in Julia, which can be useful for various applications such as updates, polling, or any task that needs to be performed at regular intervals.