Run work on a schedule
A scheduled job is work the platform starts on a timetable. At each due
time it records an instance and sends a signed POST (a firing) to your application, which
does the work and, if the job asks for it, reports when it finished. This page sets one up end to
end.
1. Declare the job
Section titled “1. Declare the job”Declare scheduled jobs with the rest of your definitions. The
application’s service account has scheduled-job:sync for its own application.
set := sync.ForApplication("orders"). AddScheduledJob(sync.MakeScheduledJob("orders:nightly-reconcile", "Nightly reconcile", "0 0 2 * * *"). WithTimezone("Europe/London"). WithTargetURL("https://orders.example.com/webhooks/scheduled-job"). TracksCompletionEnabled(). WithTimeout(30))var set = Definitions.DefinitionSet.define("orders") .withScheduledJobs(List.of(Definitions.ScheduledJob .of("orders:nightly-reconcile", "Nightly reconcile", List.of("0 0 2 * * *")) .withTimezone("Europe/London") .withTargetUrl("https://orders.example.com/webhooks/scheduled-job") .withTracksCompletion(true)));const definitions = sync .defineApplication("orders") .withScheduledJobs([ { code: "orders:nightly-reconcile", name: "Nightly reconcile", crons: ["0 0 2 * * *"], timezone: "Europe/London", targetUrl: "https://orders.example.com/webhooks/scheduled-job", tracksCompletion: true, clientId: null, // platform-scoped; set a client for a per-tenant job }, ]) .build();use FlowCatalyst\Attributes\AsScheduledJob;use FlowCatalyst\ScheduledJobs\HandlesScheduledJob;
// No targetUrl: the sync points the job at the route the SDK mounts// (APP_URL + /api/_fc/scheduled-jobs/process), and that route calls handle().#[AsScheduledJob( code: 'orders:nightly-reconcile', name: 'Nightly reconcile', crons: ['0 0 2 * * *'], timezone: 'Europe/London', tracksCompletion: true,)]final class NightlyReconcile implements HandlesScheduledJob{ public function handle(array $envelope, callable $log): mixed { $log('starting reconcile'); // ... the work; throw to report a failure ... return ['reconciled' => 42]; // the completion result }}php artisan flowcatalyst:scan && php artisan flowcatalyst:sync registers it.
let set = DefinitionSet::for_application("orders").add_scheduled_job( ScheduledJobDefinition::make("orders:nightly-reconcile", "Nightly reconcile") .add_cron("0 0 2 * * *") .with_timezone("Europe/London") .with_target_url("https://orders.example.com/webhooks/scheduled-job") .with_tracks_completion(true),);Cron has six fields, seconds first: second minute hour day-of-month month day-of-week, so
0 0 2 * * * is 02:00:00 every day. A five-field expression is refused (CRON_INVALID_SHAPE).
Jobs saved by older releases with five fields were converted (a 0 seconds field added) and, having
never fired, set to PAUSED; resume the ones you want. See the cron reference.
Choose the settings with the receiver in mind:
| Setting | Use |
|---|---|
tracksCompletion |
true when you want each run’s outcome recorded. The instance stays open until the receiver reports. |
concurrent |
false (the default) means “never two runs at once”. The receiver enforces it, with a lock; the platform fires every slot regardless. |
timeoutSeconds |
How long the platform waits for the HTTP answer (default 10, at most 300) and the budget passed to the receiver. Answer fast and work in the background. |
deliveryMaxAttempts |
How many times a firing is sent before it counts as undeliverable (default 3). |
payload |
Fixed JSON passed with every firing. |
| client | Omit for a platform-wide job. A job that belongs to one tenant names its client. |
2. Receive firings
Section titled “2. Receive firings”Each firing is a JSON POST with jobId, jobCode, instanceId, scheduledFor (absent for a
manual firing), firedAt, triggerKind (CRON or MANUAL), payload, tracksCompletion,
concurrent and timeoutSeconds. It is signed like any delivery, always by the owning
application’s service account, so verify it with that account’s signing secret
(FLOWCATALYST_SIGNING_SECRET; see receive webhooks).
The SDK runners do the rest: look up the handler by jobCode, take the overlap lock, answer 202 at
once, run the handler in the background, and report completion (the handler’s return value as the
result, a thrown error as a failure).
verifier := webhook.NewVerifier(os.Getenv("FLOWCATALYST_SIGNING_SECRET"))runner := scheduledjobs.NewBuilder(fcClient, postgreslock.New(pool)). LockTTL(15 * time.Minute). Handler("orders:nightly-reconcile", func(ctx context.Context, h *scheduledjobs.HandlerContext) (json.RawMessage, error) { h.Log(ctx, "starting reconcile", nil) // ... the work; honour ctx, which carries the job's timeout ... return json.RawMessage(`{"reconciled":42}`), nil }). Build()
http.HandleFunc("POST /webhooks/scheduled-job", func(w http.ResponseWriter, r *http.Request) { raw, _ := io.ReadAll(r.Body) if err := verifier.Verify(raw, r.Header.Get(webhook.SignatureHeader), r.Header.Get(webhook.TimestampHeader)); err != nil { http.Error(w, "invalid signature", http.StatusUnauthorized) return } switch res := runner.Process(raw); res.Kind { case scheduledjobs.ResultAccepted: w.WriteHeader(http.StatusAccepted) case scheduledjobs.ResultNotFound: http.Error(w, res.Message, http.StatusNotFound) default: http.Error(w, res.Message, http.StatusBadRequest) }})fcClient is a platform client with the service account’s credentials (it reports logs and
completion). Use lock.NewMemory() only for a single process; postgreslock or redislock
across replicas.
The Java SDK has no runner: verify the firing, answer 202, do the work, and report completion
with the client.
WebhookSignature.verify(rawBody, signatureHeader, timestampHeader, signingSecret);JsonNode firing = mapper.readTree(rawBody);String instanceId = firing.get("instanceId").asText();// answer 202 now, then:executor.submit(() -> { client.scheduledJobs().logForInstance(instanceId, new WriteInstanceLogRequest().level("INFO").message("starting reconcile")); String outcome = "SUCCESS"; try { reconcile(); } catch (Exception e) { outcome = "FAILURE"; } if (firing.get("tracksCompletion").asBoolean()) { client.scheduledJobs().completeInstance(instanceId, new CompleteInstanceRequest().status(outcome)); }});WriteInstanceLogRequest and CompleteInstanceRequest are the SDK’s generated models
(io.flowcatalyst.sdk.generated.model).
Enforce concurrent: false yourself (for example with a database advisory lock per job code).
import { PgLockProvider, verifyDeliverySignature } from "@flowcatalyst/sdk";
// PgLockProvider uses an fc_locks table: create it once with initLockSchema(pool).const runner = client .scheduledJobRunner({ lockProvider: new PgLockProvider(pool) }) .handler("orders:nightly-reconcile", async ({ envelope, log }) => { await log("starting reconcile"); // ... the work; throw to report a failure ... return { reconciled: 42 }; // the completion result });
// any HTTP framework; it must give you the raw request bodyapp.post("/webhooks/scheduled-job", async (req, reply) => { verifyDeliverySignature({ rawBody: req.rawBody, signature: req.headers["x-flowcatalyst-signature"], timestamp: req.headers["x-flowcatalyst-timestamp"], secret: process.env.FLOWCATALYST_SIGNING_SECRET!, }); const result = await runner.process(JSON.parse(req.rawBody)); reply.code(result.status).send(result.bodyJson);});The default lock provider (NoOpLockProvider) never blocks; use PgLockProvider or
RedisLockProvider when concurrent: false matters.
Nothing more to write. The SDK mounts POST /api/_fc/scheduled-jobs/process, guarded by the
fc-signature middleware, which fails closed when FLOWCATALYST_SIGNING_SECRET is unset. Each
scanned #[AsScheduledJob] class with a handle() method is its handler, and a cache lock
(CacheLockProvider) prevents overlap. To register a handler in code instead:
app(\FlowCatalyst\ScheduledJobs\ScheduledJobRunner::class) ->handler('orders:nightly-reconcile', fn (array $envelope, callable $log) => ['reconciled' => 42]);Laravel runs the handler before the request ends, so keep it short or put the work on Laravel’s
queue. FLOWCATALYST_SCHEDULED_JOBS_PROCESS_URL overrides the target URL when the reachable
address is not APP_URL.
The Rust SDK has no scheduled-job runner. Verify the firing with WebhookVerifier, answer
202, and call POST /api/scheduled-jobs/instances/{instanceId}/complete when the work is
done.
What your answer does
Section titled “What your answer does”| You answer | The instance |
|---|---|
2xx (the runners send 202) |
DELIVERED; with tracksCompletion, COMPLETED once you report |
429 |
Re-queued for Retry-After (30 seconds when absent); no attempt spent |
422 with FlowCatalyst-Outcome: reject |
DELIVERY_FAILED at once |
| Anything else, or nothing within the timeout | Sent again, up to deliveryMaxAttempts, then DELIVERY_FAILED |
Missed slots are not replayed: after an outage the job fires once, for the latest slot. If the work
must cover a gap, use scheduledFor and your own record of the last successful run.
3. Report progress and completion
Section titled “3. Report progress and completion”With tracksCompletion: true, an instance stays DELIVERED (shown as running) until the receiver
calls POST /api/scheduled-jobs/instances/{instanceId}/complete with SUCCESS or FAILURE and an
optional result. Progress lines go to POST /api/scheduled-jobs/instances/{instanceId}/log. The
runners do both for you; the service account’s scheduled-job-instance:write permission allows it.
When a runner finds the lock for a non-concurrent job already held, it does not run the handler; for
a job that tracks completion it reports a failure with the reason lock-held, so overlapping runs
are visible rather than silent.
4. Fire a job on demand
Section titled “4. Fire a job on demand”An application can fire its own jobs, for example to run the nightly reconcile right after an
import. Look the job up by code, then fire it; the instance is MANUAL and goes through the same
path, receiver included.
job, err := c.ScheduledJobs().GetByCode(ctx, "orders:nightly-reconcile", "" /* clientID */)if err != nil { return err }fired, err := c.ScheduledJobs().Fire(ctx, job.ID, &client.FireRequest{CorrelationID: importID})var job = client.scheduledJobs().getByCode("orders:nightly-reconcile");client.scheduledJobs().fire(job.getId(), new FireNowRequest().correlationId(importId));const job = await client.scheduledJobs().getByCode("orders:nightly-reconcile");if (job.isOk()) await client.scheduledJobs().fire(job.value.id, { correlationId: importId });$job = FlowCatalyst::scheduledJobs()->getByCode('orders:nightly-reconcile');$instanceId = FlowCatalyst::scheduledJobs()->fire($job->id, correlationId: $importId);A paused job can be fired by hand; an archived one cannot. Administrators can also fire any job from the console’s Scheduled jobs page, which lists every instance with its attempts and logs.
Related
Section titled “Related”- Scheduled jobs: firing, instances, the once-per-slot guarantee and retention.
- Cron syntax.
- Receive deliveries and verify signatures.
- Go SDK scheduled jobs.