Writing handlers
The handler is the function a job runs. In Node.js it can be sync or async; in .NET it returns a Task (Func<JobContext, Task>).
How the handler ends decides how the run is recorded:
| The handler | The run is recorded as |
|---|---|
| Returns (any value) | success |
| Throws | failed, with the error message |
| Runs past its timeout | failed, with TimeoutError (TimeoutException in .NET) |
Throws after a stop or a takeover cancelled the run (ctx.signal, ctx.CancellationToken) |
interrupted (not a failure) |
The context: ctx
Section titled “The context: ctx”Every handler receives one argument: the run’s context (JobContext in both languages).
| Node.js | .NET | Meaning |
|---|---|---|
name |
Name |
The job’s name |
slot |
Slot (long) |
The scheduled time in ms since 1970. The same on every instance and every attempt |
scheduledAt (Date) |
ScheduledAt (DateTimeOffset) |
The slot as a time. When the run was due, not when it started |
instanceId |
InstanceId |
The instance running this (you) |
attempt |
Attempt |
1 for the first try; 2 or more when a backup took over |
reason |
Reason (RunReason) |
Why this run started: scheduled, manual, catch-up or takeover |
manual |
IsManual |
true when started with runNow(), RunNowAsync() |
signal (AbortSignal) |
CancellationToken |
Fires when the run should stop |
data |
Data, GetData<T>() |
The data you gave the scheduler, the job or the manual run. See Run data |
Stopping when asked
Section titled “Stopping when asked”The run’s cancellation (ctx.signal aborts, ctx.CancellationToken is cancelled) fires in three situations:
flowchart LR
stop["the scheduler is stopping<br/>(shutdown, deploy)"] --> sig(("the run is<br/>cancelled"))
timeout["its timeout passed"] --> sig
lost["a backup took the run over<br/>(this instance stopped<br/>renewing its lease)"] --> sig
sig --> handler["your handler should stop<br/>and throw"]
anarchon can’t stop your function from outside; neither JavaScript nor .NET has a way to do that. The signal or token is a request, and the handler has to honor it.
In a loop
Section titled “In a loop”Check between units of work. ctx.signal.throwIfAborted() and ctx.CancellationToken.ThrowIfCancellationRequested() throw if the run was cancelled, and do nothing otherwise:
Passing it on
Section titled “Passing it on”Many APIs accept a signal or a token and stop on their own:
Waiting
Section titled “Waiting”Waits take it too:
Why throw, and not just return?
Section titled “Why throw, and not just return?”On a lease backend the difference matters:
- If the handler throws after a stop cancelled the run, the run is recorded as
interruptedand handed to another instance, which starts it again as the next attempt. - If the handler returns, the run counts as finished. Nobody continues it.
So: throw when the work isn’t done, and return when it is.
Make jobs safe to run twice
Section titled “Make jobs safe to run twice”anarchon guarantees one winner per attempt, not one execution per run. A run can execute more than once:
- The runner crashes halfway. A backup starts the run again from the beginning.
- The runner freezes longer than its lease. A backup takes over, and when the frozen one wakes up it runs for a moment before it learns it lost the run.
The fix is to write jobs that are idempotent: running them twice has the same effect as running them once. The slot (ctx.slot, ctx.Slot) is the tool for that, because it is the same number on every attempt of the same run.
Use the slot as a key
Section titled “Use the slot as a key”Use the slot as an idempotency key for other services
Section titled “Use the slot as an idempotency key for other services”Work on a time window, not on “now”
Section titled “Work on a time window, not on “now””A takeover can start minutes after the slot. If the job asks “what happened in the last hour” using the current time, a late attempt covers a different hour. Use the slot:
A window tied to one slot gets done only if that slot runs, and a run can be skipped (see Guarantees and limits). If every hour must be rolled up, have each run also do the earlier hours that are still missing:
Reject writes from an older attempt
Section titled “Reject writes from an older attempt”An idempotent write makes a second attempt harmless when the attempts run one after the other. When they overlap (a frozen runner wakes up and writes before it learns that a backup took over), the older attempt can overwrite what the newer one wrote. On a lease backend, every attempt of a run has a higher attempt number than the one before, so the slot and the attempt together work as a fencing token: store the attempt with the row, and let a write apply only if its attempt isn’t older.
The same pair goes to another service as a version: reject a request whose (slot, attempt) is lower than one already seen. On a claim-only backend, the attempt is always 1 and nobody takes a run over, so there is nothing to fence.
Knowing it’s a retry
Section titled “Knowing it’s a retry”The attempt and the reason tell you that a previous attempt started and didn’t finish:
Errors
Section titled “Errors”A handler that throws is recorded as failed. anarchon does not retry failed runs: the next run is the next scheduled slot.
If you want retries for errors, do them inside the handler:
To be told about failures, listen for the failure event (failure, Failed).
Long jobs
Section titled “Long jobs”A job may run longer than its interval. With the default overlap (skip) the runs due meanwhile are skipped, so there is one at a time. For long jobs:
- Set a timeout, so a hung run can’t block the job forever.
- Check the run’s cancellation often, so shutdowns are quick.
- Keep the job idempotent, because a long job is more likely to be interrupted.
Long-running jobs has a complete example with checkpoints.
- Lifecycle: start, stop and graceful shutdown
- Events and logging