Skip to content

Petrichor.Timer#

Petrichor.Timer provides cancellable wall-clock timers built on Petrichor.Task.

Loading#

local Timer = require("Petrichor.Timer")
import * as Timer from "Petrichor.Timer"

Handles#

Each timer returns a handle with:

Method Description
handle:cancel() Stop future callbacks. The current callback may still finish.
handle:is_cancelled() True if cancel() was called.

API#

Timer.after(seconds, fn) -> handle#

Call fn(handle) once after seconds.

Timer.after(2.0, function(h)
    Log.info("my-mod", "two seconds elapsed")
end)
Timer.after(2.0, (h) => {
    Log.info("my-mod", "two seconds elapsed")
})

Timer.every(seconds, fn) -> handle#

Call fn(handle) every seconds until cancelled.

Timer.after_then_every(delay, interval, fn) -> handle#

Wait delay seconds, call fn once, then call fn every interval seconds until cancelled.


Example#

local Timer = require("Petrichor.Timer")
local Log   = require("Petrichor.Log")

local MyMod = mod("timer-demo")

function MyMod:init()
    self._pulse = Timer.every(1.0, function()
        Log.info("timer-demo", "pulse")
    end)
end

function MyMod:shutdown()
    self._pulse:cancel()
end
import * as Timer from "Petrichor.Timer"
import * as Log from "Petrichor.Log"

declare function mod(name: string): any
const MyMod = mod("timer-demo")

MyMod.init = function () {
    this._pulse = Timer.every(1.0, () => {
        Log.info("timer-demo", "pulse")
    })
}

MyMod.shutdown = function () {
    this._pulse.cancel()
}

export = MyMod

See also#