Skip to content

Scheduled jobs

A scheduled job is a cron-driven definition on the platform. When a slot comes due the platform records an instance and sends a signed POST (the firing) to the job’s target URL. The scheduledjobs package is the receiving side: it validates the firing, finds the handler for the job code, runs it in the background, and reports logs and the outcome back to the platform.

Declaring the job is done with sync or the console. This page covers what happens when the firing arrives.

import (
"github.com/flowcatalyst/go-sdk/client"
"github.com/flowcatalyst/go-sdk/lock"
"github.com/flowcatalyst/go-sdk/scheduledjobs"
)
runner := scheduledjobs.NewBuilder(apiClient, lock.NewMemory()).
LockTTL(15 * time.Minute).
OnError(func(err error, env *scheduledjobs.Envelope) {
log.Printf("runner: %s instance=%s: %v", env.JobCode, env.InstanceID, err)
}).
Handler("orders:daily-rollup", dailyRollup).
Build()

NewBuilder(api, lockProvider) takes the API client used for the log and completion callbacks, and a lock.Provider. Pass lock.NewNoOp() if you do not want locking.

A handler has this signature:

func dailyRollup(ctx context.Context, hctx *scheduledjobs.HandlerContext) (json.RawMessage, error) {
hctx.Log(ctx, "starting", nil)
// ... work; honour ctx for cancellation ...
return json.RawMessage(`{"rolledUp":42}`), nil
}
  • Return a JSON value to store it as the instance’s completion_result, or nil, nil for an empty success.
  • Return an error to record a failure. The error text is stored with the instance.
  • A panic is recovered and treated as an error.
  • hctx.Envelope is the firing; hctx.Log(ctx, message, &scheduledjobs.LogOptions{Level: "WARN", Metadata: raw}) appends a log line to the instance (levels DEBUG, INFO, WARN, ERROR; default INFO). Logging is best effort: a failure goes to your OnError hook and never fails the handler.

The handler key is the job’s code as the platform sends it in jobCode. Use the full code the job was defined with.

Runner.Process(raw json.RawMessage) Result is the entry point. It decodes the body, picks the handler, starts it on a goroutine and returns immediately, so the platform’s request does not wait for the work.

mux.HandleFunc("POST /webhooks/scheduled-job", func(w http.ResponseWriter, req *http.Request) {
raw, err := io.ReadAll(req.Body)
if err != nil {
http.Error(w, `{"error":"read body"}`, http.StatusBadRequest)
return
}
// Verify the signature first: see below.
switch res := runner.Process(raw); res.Kind {
case scheduledjobs.ResultAccepted:
w.WriteHeader(http.StatusAccepted)
case scheduledjobs.ResultNotFound:
http.Error(w, res.Message, http.StatusNotFound)
case scheduledjobs.ResultBadRequest:
http.Error(w, res.Message, http.StatusBadRequest)
}
})
Result When Status to answer
ResultAccepted A handler is registered and was started. 202
ResultBadRequest The body is not valid JSON, or triggerKind is not CRON or MANUAL. 400
ResultNotFound No handler is registered for jobCode. 404

Runner.Wait() blocks until every in-flight handler finishes. Call it on shutdown so a deploy does not cut a job in half. RegisteredCodes() lists the registered handler codes, for diagnostics.

scheduledjobs.Envelope is the decoded body:

Field JSON Meaning
JobID, JobCode jobId, jobCode Which job.
InstanceID instanceId This firing. Use it for logs, completion and your own idempotency.
ScheduledFor scheduledFor The cron slot (absent for a manual firing).
FiredAt firedAt When the instance was created.
TriggerKind triggerKind CRON or MANUAL (TriggerCron, TriggerManual).
CorrelationID correlationId Present when the firing was started with one.
Payload payload The job’s payload.
TracksCompletion tracksCompletion Whether the platform waits for your completion report.
TimeoutSeconds timeoutSeconds The job’s timeout.

The platform sends a concurrent member too. The Go envelope does not decode it; see locking.

When the job has tracksCompletion, the runner reports the outcome after the handler finishes, with POST /api/scheduled-jobs/instances/{instanceId}/complete:

  • success: status SUCCESS and your returned JSON as the result;
  • failure: status FAILURE and {"error": "<message>"}.

A result larger than scheduledjobs.MaxResultBytes (10,000 bytes) is replaced by {"truncated": true, "preview": "..."}. Until the report arrives the instance stays DELIVERED and the job shows as running. If the job does not track completion, nothing is reported and a handler failure reaches only your OnError hook.

If the envelope carries a timeoutSeconds, the handler’s ctx is cancelled after that long. The context is not the HTTP request’s: it is a background context, so it survives the 202 response. Note that timeoutSeconds is also the platform’s HTTP timeout for the firing call (10 seconds when the job sets none, at most 300), so set it to cover the handler’s real run time, not just the call. A job with no timeoutSeconds in the envelope runs without a deadline.

The runner serialises firings with a lock so two replicas do not run the same job at once. With the default builder settings it acquires the key scheduled-job:{jobCode} for LockTTL (default 10 minutes) before every handler. If the lock is held:

  • the handler is not run;
  • if the job tracks completion, the runner reports FAILURE with {"skipped": true, "reason": "lock-held"}, so the operator sees the firing was skipped rather than lost.

A lock failure (backend error) goes to OnError as ErrLockFailed and the handler does not run.

Builder method
EnforceLock(bool) Turn locking off. Default on.
LockTTL(d) Default scheduledjobs.DefaultLockTTL, 10 minutes. Make it longer than the longest run. The lock is released when the handler returns.
LockKey(func(*Envelope) string) Change the key, for example to lock per client as well as per job.

The platform never prevents overlap: it fires every slot whatever the last instance is doing, and it tells the receiver whether the job is concurrent. Overlap protection is yours.

Use a lock backend that spans your replicas. lock.NewMemory() only protects one process. See Locks and cache.

OnError(func(err error, env *Envelope)) is called, synchronously inside the background goroutine, for every failure the runner cannot report any other way. The error is a *scheduledjobs.RunnerError whose Kind is one of:

Kind Meaning
ErrCallbackFailed The log or completion API call failed.
ErrLockFailed Acquiring or releasing the lock failed.
ErrHandlerPanicked The handler returned an error or panicked. (The name covers both.)
var re *scheduledjobs.RunnerError
if errors.As(err, &re) && re.Kind == scheduledjobs.ErrLockFailed {
metrics.LockFailures.Inc()
}

If you send the hook to another goroutine, copy what you need from env first.

The client.ScheduledJobs() resource lets the application drive jobs: Fire (create a MANUAL instance), Pause, Resume, Archive, ListInstances, GetInstance, ListInstanceLogs, LogForInstance and CompleteInstance. The runner uses the last two for you.