Skip to content

Lesson 6: Work with timers

Goal: a /remind command and a repeating timer you cancel yourself.

--! name: Reminder
--! description: /remind says "time is up" after a minute
--! api: 1
--! permissions: send
swizzin.command("remind", function(ctx, args)
local target = ctx.target
if target == nil then return end
swizzin.timer.after(60000, function()
swizzin.send(target, "Time is up")
end)
end, "Remind this channel in one minute")
-- a repeating timer that stops itself after 3 runs
local runs = 0
local id
id = swizzin.timer.every(1000, function()
runs += 1
swizzin.log("tick", runs)
if runs >= 3 then swizzin.timer.cancel(id) end
end)

timer.after(ms, fn) runs once (0 to 86,400,000 ms). timer.every(ms, fn) repeats (at least 100 ms). timer.cancel(id) stops one. A timer keeps the network context it was created in.

/remind in a channel sends Time is up there a minute later. The Console shows tick 1, tick 2, tick 3 once per second after the script loads.

  • Never cancelling repeating timers: a script may have at most 32, and all stop when the script stops.
  • Reading ctx later: copy what you need (like target) into a local first.
  • Slow timer callbacks: each must finish within 250 ms.
  • Nothing fires: confirm the script is On and check the Console for errors.