Ephemeral thread-based task scheduler used to run tasks at a specific time.
const Task = union(enum) {
say: []const u8,
pub fn run(task: Task, ctx: void, at: i64) void {
_ = at;
_ ctx;
switch (task) {
.say => |msg| {std.debug.print("{s}\n", .{msg}),
}
}
}
...
var s = zul.Scheduler(Task, void).init(allocator);
defer s.deinit();
try s.start({});
try s.scheduleIn(.{.say = "world"}, std.time.ms_per_s * 5);
try s.schedule(.{.say = "hello"}, std.time.milliTimestamp() + 100);
zul.Scheduler(T)
is a thread-safe way to schedule tasks for future execution. Tasks can be scheduled using the schedule()
, scheduleIn()
or scheduleAt()
methods. These methods are thread-safe.
The scheduler runs in its own thread (started by calling start()
). Importantly, tasks are run within the scheduler thread and thus can delay each other. Consider having your tasks use zul.ThreadPool in more advanced cases.
Tasks are not persisted (e.g. if the schedule or program crashes, scheduled jobs are lost). Otherwise, the scheduler never discards a task. Tasks that were scheduled in the past are run normally. Applications that care about stale tasks can use the last parameter passed to T.run
which is the original scheduled timestamp (in milliseconds).
T
must have a run
method. Two variants are supported:
start(self: *Scheduler(T), ctx: C) !void
Launches the task scheduler in a new thread. This method is thread-safe. An error is returned if start is called multiple times.
The provided ctx
will be passed to T.run
. In cases where no ctx is needed, a void
context should be used, as shown in the initial example.
stop(self: *Scheduler(T)) void
Stops the task scheduler. This method is thread-safe. It is safe to call multiple times, even if the scheduler is not started. Since deinit
calls this method, it is usually not necessary to call it.