Cruma
DashboardDownload

Define jobs in code

A runner can declare the scheduled jobs it serves next to the handlers that run them: the name, cron schedule, time zone, overlap, retries, missed-run and delivery settings and which outcomes notify. Each time the runner connects it sends its declarations to Tron, and Tron creates each job or brings it in line with the declaration. The schedule then lives in your repository: it is reviewed in a pull request, deployed with the code that runs it, and set up the same way in every environment.

A handler without a declaration behaves exactly as described in Runners: its job is made by hand in Tron.

Declare a job

Each example declares a job that runs every day at 05:30 Stockholm time and registers a second handler without a declaration. The Rust, Python and TypeScript examples are complete runners; the .NET and Go examples continue the runner from Write a runner. Each example is checked against its package by that package's tests.

Rust

Register the handler with on_job instead of on to declare its job.

use cruma_tron_runner::{
    protocol::{NotificationEvent, OverlapPolicy, RetryBackoff},
    DeliveryMode, Endpoint, FileSecretStore, JobDeclaration, MissedRun, Retries, Runner,
};

let endpoint = Endpoint::from_base_url(&std::env::var("TRON_URL")?)?;
let nightly = JobDeclaration::new("nightly-report", "0 30 5 * * *") // cron with a seconds field
    .time_zone("Europe/Stockholm")
    .overlap_policy(OverlapPolicy::Skip)
    .retry_policy(Retries::new(3, RetryBackoff::Exponential, 30, 600).on_err())
    .missed_run(MissedRun::DeferredUntilRunner { limit: 1 })
    .delivery_mode(DeliveryMode::OneRunner)
    .delivery_timeout_seconds(30)
    .lateness_threshold_seconds(600)
    .notifications([NotificationEvent::Failed, NotificationEvent::Missed], None);
let runner = Runner::builder(endpoint, std::env::var("TRON_WORKER_KEY")?)
    .secret_store(FileSecretStore::new(std::env::var("TRON_SECRET_DIR")?)?)
    .on_job("send-report", nightly, |job| async move { Ok(format!("sent the report for {}", job.job_name)) })
    .on("ad-hoc", |_| async { Ok("ran".to_owned()) }) // a handler without a declaration, exactly as before
    .connect()
    .await?;

Python

Pass the declaration as job= to @runner.handler or runner.register.

import os

from tron_runner import (
    DeferMissedUntilRunner, Delivery, FileSecretStore, JobDeclaration, NotificationEvent, Notifications, Ok, OneRunner,
    Outcome, OverlapPolicy, Retries, RetryBackoff, Runner,
)

runner = Runner(
    os.environ["TRON_URL"],
    os.environ["TRON_WORKER_KEY"],
    secret_store=FileSecretStore(os.environ["TRON_SECRET_DIR"]),
)

nightly = JobDeclaration(
    "nightly-report",
    "0 30 5 * * *",  # cron with a seconds field
    time_zone="Europe/Stockholm",
    overlap_policy=OverlapPolicy.SKIP,
    retries=Retries(3, RetryBackoff.EXPONENTIAL, backoff_seconds=30, max_backoff_seconds=600, on_err=True),
    missed_run=DeferMissedUntilRunner(limit=1),
    delivery_mode=OneRunner(),
    delivery_timeout_seconds=30,
    lateness_threshold_seconds=600,
    notifications=Notifications([NotificationEvent.FAILED, NotificationEvent.MISSED]),
)

@runner.handler("send-report", job=nightly)
async def send_report(delivery: Delivery) -> Outcome:
    return Ok(f"sent the report for {delivery.job_name}")

@runner.handler("ad-hoc")  # a handler without a declaration, exactly as before
async def ad_hoc(delivery: Delivery) -> Outcome:
    return Ok("ran")

TypeScript

Pass the declaration as the third argument of runner.handle.

import { FileSecretStore, ok, Runner, type JobDeclaration } from "@cruma-io/tron-runner";

const runner = new Runner({
  url: process.env.TRON_URL!,
  token: process.env.TRON_WORKER_KEY!,
  secretStore: new FileSecretStore(process.env.TRON_SECRET_DIR!),
});

const nightly: JobDeclaration = {
  name: "nightly-report",
  cron: "0 30 5 * * *", // cron with a seconds field
  timeZone: "Europe/Stockholm",
  overlapPolicy: "skip",
  retries: { maxAttempts: 3, backoff: "exponential", backoffSeconds: 30, maxBackoffSeconds: 600, onErr: true },
  missedRun: { policy: "deferred_until_runner", limit: 1 },
  deliveryMode: { mode: "one_runner" },
  deliveryTimeoutSeconds: 30,
  latenessThresholdSeconds: 600,
  notifications: { events: ["failed", "missed"] },
};

runner.handle("send-report", (delivery) => ok(`sent the report for ${delivery.jobName}`), nightly);
runner.handle("ad-hoc", () => ok("ran")); // a handler without a declaration, exactly as before

// A refusal or conflict is logged as a warning; every answer, with its typed reason, also arrives here.
runner.on("jobDeclared", (result) => {
  if (result.outcome.status === "refused") console.warn(`${result.name} was refused: ${result.outcome.reason}`);
});

await runner.start();

.NET

Pass the declaration as the third argument of runner.Handle. A declaration without Name names the job after its handler key, here cleanup-search-logs. A file that also imports Cruma.Tron.Runner.Generated needs using JobDeclaration = Cruma.Tron.Runner.JobDeclaration;.

runner.Handle(
    "cleanup-search-logs",
    (delivery, cancellationToken) => Task.FromResult(Outcome.Ok("cleaned")),
    new JobDeclaration
    {
        Cron = "0 30 5 * * *", // cron with a seconds field
        TimeZone = "Europe/Stockholm",
        Overlap = Overlap.Skip,
        Retries = new Retries { MaxAttempts = 3, Backoff = Backoff.Exponential, BackoffSeconds = 30, MaxBackoffSeconds = 600, OnErr = true },
        MissedRun = MissedRun.DeferUntilRunner(limit: 1),
        DeliveryMode = DeliveryMode.OneRunner,
        LatenessThresholdSeconds = 600,
        Notify = new Notifications { Events = [NotifyOn.Failed, NotifyOn.Missed] },
    });

// A handler without a declaration, exactly as before.
runner.Handle("ad-hoc", (delivery, cancellationToken) => Task.FromResult(Outcome.Ok("ran")));

Go

Pass tronrunner.WithJob(...) to runner.Handle. The example also imports time and the package's generated subpackage, github.com/umbra-yurei/tron-runner-sdk/packages/go/generated, for the setting values.

runner, err := tronrunner.New(tronrunner.Config{
	BaseURL:     os.Getenv("TRON_URL"),
	Token:       os.Getenv("TRON_WORKER_KEY"),
	SecretStore: store,
	Hooks: tronrunner.Hooks{
		// A refusal or conflict is logged as a warning; every answer, with its typed reason, also arrives here.
		OnJobDeclared: func(result tronrunner.JobDeclared) {
			if result.Outcome.Status == generated.Refused {
				log.Printf("%s was refused: %s", result.Name, *result.Outcome.Reason)
			}
		},
	},
})
if err != nil {
	return err
}

nightly := tronrunner.JobDeclaration{
	Name:     "nightly-report",
	Cron:     "0 30 5 * * *", // cron with a seconds field
	TimeZone: "Europe/Stockholm",
	Overlap:  generated.OverlapPolicySkip,
	Retries: &tronrunner.Retries{
		MaxAttempts: 3, Backoff: generated.Exponential, InitialWait: 30 * time.Second, MaxWait: 10 * time.Minute, OnErr: true,
	},
	MissedRun:         tronrunner.DeferMissedRuns(1),
	Delivery:          tronrunner.DeliverToOneRunner(),
	DeliveryTimeout:   30 * time.Second,
	LatenessThreshold: 10 * time.Minute,
	Notifications:     &tronrunner.Notifications{Events: []generated.NotificationEvent{generated.Failed, generated.Missed}},
}
err = runner.Handle("send-report", func(ctx context.Context, d tronrunner.Delivery) tronrunner.Outcome {
	return tronrunner.Ok("sent the report for " + d.JobName)
}, tronrunner.WithJob(nightly))
if err != nil {
	return err
}
// A handler without a declaration, exactly as before.
runner.Handle("ad-hoc", func(context.Context, tronrunner.Delivery) tronrunner.Outcome { return tronrunner.Ok("ran") })

The declaration's settings:

SettingRequiredMeaning
NameyesThe job's name. Unique among one runner's declarations. In .NET it defaults to the handler key.
CronyesSix fields with seconds first: 0 30 5 * * * is 05:30:00 every day.
Time zonenoIANA name such as Europe/Stockholm that the cron expression is read in. Default UTC.
OverlapnoWhat a new occurrence does while an earlier run is open: allow, skip or queue one.
RetriesnoTotal attempts, fixed or exponential backoff with its base and maximum wait, and which runner failures retry: a reported error, no acceptance in time, or a disconnect. Default: one attempt.
Missed runnoSkip a missed occurrence (the default), or defer up to a limit until a runner connects.
Delivery modenoOne runner (the default), every connected runner, at most N or at least N.
Delivery timeoutnoSeconds a runner has to accept a delivery. Default 30.
Lateness thresholdnoSeconds after the due time a result still counts as on time. Default 60.
Miss gracenoSeconds after the due time a run may still start.
NotificationsnoThe outcomes that notify (failed, recovered, missed, late, every run) and an optional reminder interval.

Two things are never declared:

  • Who is notified. Recipients are chosen on the job in Tron. A declaration with notifications sets which events notify; the first one gives the job a notification rule with no recipients until you add them. A declaration without notifications leaves the job's notification settings alone.
  • Required runner labels. A declared job requires exactly the labels its worker key allows (see Route work with labels), so only runners of that key that announce all of them run it.

A runner declares at most 128 jobs.

What Tron answers

Tron answers every declaration separately, each time the runner connects:

AnswerMeaning
appliedThe job was created, or changed to match the declaration.
unchangedThe job already matched. Reconnecting writes nothing.
refusedNothing changed. The answer carries a reason, below.
conflictAnother runner of the same worker key declares this job differently. See "Rolling deploys" below.

Every SDK logs each answer, a refusal or conflict as a warning with its reason, and hands it to your code: Event::JobDeclared in Rust, on_job_declared in Python, the jobDeclared event in TypeScript, the JobDeclared event in .NET and Hooks.OnJobDeclared in Go.

A refused declaration never stops the runner. Its handler, every other handler and every other declaration keep working. The reasons:

ReasonCause
invalid_nameThe name is blank.
duplicate_nameTwo declarations of one runner share a name; all of them are refused.
unknown_handler_keyThe handler the declaration names is not registered.
invalid_cronThe cron expression does not parse.
unknown_time_zoneThe time zone is not a known IANA name.
setting_out_of_rangeA timeout, threshold, limit, miss grace, retry setting or reminder interval is outside what a job allows.
name_managed_elsewhereA job with this name is made by hand or managed by Terraform. See "Move a hand-made job into code" below.
live_job_limit_reachedCreating the job would exceed the live-job limit.
not_storedTron could not save it. The runner's next connection tries again.

If Tron does not take declarations, the SDK logs declarations not supported by this server once, connects without them, and serves every handler as usual.

One manager per job

Every job has exactly one manager: by hand (the web UI and the API), code (a runner's declaration) or Terraform. Only the manager changes a job's settings: its name, target, schedule, time zone, missed-run, delivery, lateness, overlap, retry, label and delivery-mode settings. Any other change is refused and names the manager, so a declared job cannot drift from its code.

On a job declared in code, the settings page opens read-only with This job is declared in code. The job page's Management card shows the worker key that declares it, the SDK and runner versions and when it was last declared. Whoever manages the job, you can still Run now, change its visibility and notification recipients, and delete or restore it.

A job never changes manager as a side effect of an edit. Use the Management card:

  • Manage by hand takes a code or Terraform job back into the web UI. A runner that still declares that name then has its declaration refused with name_managed_elsewhere until you rename or remove it in the code.
  • Hand to Terraform gives a hand-made job to Terraform.

Production and test keys

A declared job belongs to the worker key whose runners declare it. A runner using your production key and a runner using your test key that declare the same name create two independent jobs, each with its own settings and its key's labels. Use one worker key per environment, and declare settings that differ between environments (for example a schedule or a retry count) from your environment's configuration.

Rolling deploys

While a deployment rolls, old and new runners of one worker key are connected together and may declare the same job differently. Tron does not flip the job back and forth. It keeps following the declaration it applied while any connected runner of the key still declares it, and answers the other one conflict. The job is shown with a Declaration conflict badge, and its Management card lists both declarations with their SDK and runner versions.

When the last runner declaring the old version disconnects and exactly one other version is left, Tron applies that one by itself, without waiting for a reconnect. Versions only tell the sides apart, so a rollback converges the same way. A conflict that does not clear means runners with different declarations stay connected: check that the old deployment is really gone.

When a job is no longer declared

Removing a declaration never deletes the job straight away:

  1. When no connected runner of the job's worker key declares it any more, the job page says No live runner declares this job. Nothing else changes, so a restart or a deploy has no effect on the job.
  2. If none declares it again within a grace period of one day, Tron marks the job No longer declared and pauses it. A paused job gets no scheduled runs; you can still run it now.
  3. The job stays paused until you act: declare it again (Tron resumes it from that moment, without recording the occurrences it skipped), Manage by hand to keep it without code, or delete it.

A pause you made yourself is never lifted by Tron.

To have such jobs removed instead, turn on Auto-prune undeclared jobs for the worker key on the Runners page. Tron then deletes the key's jobs as soon as they are marked no longer declared. A deleted job keeps its run history and can be restored; turn auto-prune off for its key first, or Tron deletes the restored job again.

Move a hand-made job into code

A declaration never takes over a job made by hand or managed by Terraform: it is refused with name_managed_elsewhere. To move a hand-made job into code:

  1. Add the declaration to your runner, using the job's current settings.
  2. Delete the hand-made job, or rename it if you want to keep it side by side for a while.
  3. Deploy the runner. Tron creates the declared job on the next connection; the deleted job keeps its run history.

Notification recipients are not part of the declaration, so add them to the new job.

Next: the complete Runner protocol describes the declaration fields as they travel in announce.