Skip to content

Go SDK

Terminal window
go get chronos.sh/go

Every exported type, field and constant is documented on pkg.go.dev.

import chronos "chronos.sh/go"
client, err := chronos.NewClient(os.Getenv("CHRONOS_API_KEY"))
if err != nil {
return err
}

The import needs the chronos name because the path ends in go. NewClient rejects an empty key; the API checks the key on the first request. To check it up front, call client.Account.Get(ctx), which returns the workspace the key belongs to. A Client is safe for concurrent use, so create one and share it.

Option Default Effect
WithBaseURL(url) https://api.chronos.sh Sends requests to another Chronos API, such as a local one. Must be an absolute http or https URL.
WithHTTPClient(c) A new http.Client Sends requests with your client. It is copied, and the copy never follows redirects. Its Timeout, if set, also bounds each attempt.
WithRequestTimeout(d) 30s Bounds each attempt, including reading the response.
WithMaxRequestRetries(n) 2 Sets the retries for requests that are safe to repeat. 0 turns retries off. See Retries.
WithUserAgent(token) none Adds a product token, such as my-app/1.2.0, ahead of chronos-go/<version>.

The examples below continue from this block: client and err exist, and ctx is your context.Context.

The client has one field per resource. Every method takes a context.Context first. Request and response fields use the API’s snake_case names in JSON, and the REST reference documents every field.

Method Request Returns
Create(ctx, params) POST /v1/schedules *Schedule
List(ctx, params) GET /v1/schedules *Page[*Schedule]
Iterate(ctx, params) GET /v1/schedules, every page iter.Seq2[*Schedule, error]
Get(ctx, id) GET /v1/schedules/{id} *Schedule
Update(ctx, id, params) PATCH /v1/schedules/{id} *Schedule
Delete(ctx, id) DELETE /v1/schedules/{id} error only
Pause(ctx, id) POST /v1/schedules/{id}/pause *Schedule
Resume(ctx, id) POST /v1/schedules/{id}/resume *Schedule
Trigger(ctx, id) POST /v1/schedules/{id}/trigger *Job
Archive(ctx, id) POST /v1/schedules/{id}/archive *Schedule

Param types: ScheduleCreateParams, ScheduleUpdateParams, ScheduleListParams.

Method Request Returns
Create(ctx, params) POST /v1/jobs *Job
List(ctx, params) GET /v1/jobs *Page[*Job]
Iterate(ctx, params) GET /v1/jobs, every page iter.Seq2[*Job, error]
Get(ctx, id) GET /v1/jobs/{id} *Job
Cancel(ctx, id) POST /v1/jobs/{id}/cancel *Job
Skip(ctx, id) POST /v1/jobs/{id}/skip *Job
Retry(ctx, id) POST /v1/jobs/{id}/retry *Job
Wait(ctx, id, opts) GET /v1/jobs/{id}, polled *Job

Param types: JobCreateParams, JobListParams, JobWaitOptions.

Jobs.Create is never retried after a 5xx or a network error, because the job may already exist. To retry it yourself, set an IdempotencyKey and treat ErrorCodeIdempotencyKeyConflict as success:

_, err = client.Jobs.Create(ctx, chronos.JobCreateParams{
Name: "Charge invoice inv_789",
Handler: new("charge-invoice"),
IdempotencyKey: new("charge-inv_789"),
})
// The job already exists, so a retried create can treat this as success.
if apiErr, ok := errors.AsType[*chronos.APIError](err); ok && apiErr.Code == chronos.ErrorCodeIdempotencyKeyConflict {
err = nil
}
if err != nil {
return err
}

Jobs.Wait polls the job until it is completed, failed, cancelled or skipped, and returns it. It polls every second unless you set JobWaitOptions.PollInterval. A failed job is returned, not an error, so check its Status. Wait stops at the deadline on ctx, or after 60 seconds if ctx has none, and returns a *WaitTimeoutError holding the last state it saw (nil if no request finished):

job, err := client.Jobs.Wait(ctx, jobID, chronos.JobWaitOptions{})
if err != nil {
return err
}
fmt.Println(job.Status)
Method Request Returns
List(ctx, params) GET /v1/executions *Page[*Execution]
Iterate(ctx, params) GET /v1/executions, every page iter.Seq2[*Execution, error]
Get(ctx, id) GET /v1/executions/{id} *Execution

Param type: ExecutionListParams. Set Origin: chronos.JobOriginAPI to match executions of one-off jobs, or Search to match on the job name.

Method Request Returns
Create(ctx, params) POST /v1/monitors *Monitor
List(ctx, params) GET /v1/monitors *Page[*Monitor]
Iterate(ctx, params) GET /v1/monitors, every page iter.Seq2[*Monitor, error]
Get(ctx, id) GET /v1/monitors/{id} *Monitor
Update(ctx, id, params) PATCH /v1/monitors/{id} *Monitor
Delete(ctx, id) DELETE /v1/monitors/{id} error only
Pause(ctx, id) POST /v1/monitors/{id}/pause *Monitor
Resume(ctx, id) POST /v1/monitors/{id}/resume *Monitor
RotatePingURL(ctx, id) POST /v1/monitors/{id}/ping-url/rotate *Monitor
ListPings(ctx, id, params) GET /v1/monitors/{id}/pings *Page[*MonitorPing]
IteratePings(ctx, id, params) GET /v1/monitors/{id}/pings, every page iter.Seq2[*MonitorPing, error]

Param types: MonitorCreateParams, MonitorUpdateParams, MonitorListParams, MonitorPingListParams.

The SDK sends no pings. Your job calls monitor.PingURL with a plain HTTP request, as the Ping API describes. The URL’s token is a secret, so keep monitor.PingURL out of logs and source control.

monitor, err := client.Monitors.Create(ctx, chronos.MonitorCreateParams{
Name: "Nightly backup",
Cron: new("0 3 * * *"),
Timezone: new("Europe/London"),
GraceSeconds: new(600),
})
if err != nil {
return err
}
fmt.Println(monitor.Status) // "new" until the first success or fail ping

A failed RotatePingURL call may still have replaced the token. Before you retry, read the current URL with Get.

Method Request Returns
Get(ctx) GET /v1/account *Account

Optional request fields are pointers, and nil leaves the field out. Since Go 1.26, new(value) returns a pointer to a copy of the value:

_, err = client.Schedules.Create(ctx, chronos.ScheduleCreateParams{
Name: "Nightly report",
Cron: new("0 2 * * *"),
Timezone: new("Europe/London"),
MaxRetries: new(0), // sent as 0, not left out
Delivery: &chronos.Delivery{
Type: chronos.DeliveryTypePush,
HTTP: &chronos.HTTPDelivery{URL: "https://your-app.com/hooks/chronos", Method: "POST"},
},
})
if err != nil {
return err
}

ScheduleUpdateParams can also clear Description, Handler, Runs, StopAt and Payload, and MonitorUpdateParams can clear Description. Those fields use chronos.Nullable. Its zero value leaves the field out, chronos.NewNullable(v) sets it, and chronos.Null[T]() sends null:

_, err = client.Schedules.Update(ctx, scheduleID, chronos.ScheduleUpdateParams{
Name: new("Nightly report (EU)"),
Runs: chronos.Null[int](), // remove the run limit
})
if err != nil {
return err
}

Nullable also decodes from JSON. JSON null makes it null, a value sets it, and a field missing from the input leaves it as it was. Get() returns the value and whether it is set, and IsNull() reports whether it is null:

var update struct {
Runs chronos.Nullable[int] `json:"runs"`
}
if err := json.Unmarshal([]byte(`{"runs": null}`), &update); err != nil {
return err
}
runs, ok := update.Runs.Get()
fmt.Println(runs, ok, update.Runs.IsNull()) // 0 false true

Timestamps are time.Time, and nullable response fields are pointers. In client responses, numbers inside Payload and Result decode as json.Number, with the exact digits the API sent. ClaimedJob.Payload and PushedJob.Payload are raw JSON, so the decoder you call sets how numbers decode. The API reads numbers as 64-bit floats, so send integers above 2^53 as strings.

List returns one page, newest first, with Data and Paging:

page, err := client.Jobs.List(ctx, chronos.JobListParams{Status: chronos.JobStatusFailed, Page: 2, Size: 50})
if err != nil {
return err
}
fmt.Println(len(page.Data), page.Paging.Total)

Iterate walks every page, fetching 100 items per request unless you set Size. Each item is yielded at most once, and breaking out of the loop stops further requests. Pages are offsets, so an item deleted or changed out of your filter during the walk shifts later items onto earlier pages, and Iterate can miss some of them.

That includes changes you make yourself. Retrying a failed job moves it out of JobStatusFailed, so collect the ids before acting on them:

var failed []string
for job, err := range client.Jobs.Iterate(ctx, chronos.JobListParams{Status: chronos.JobStatusFailed}) {
if err != nil {
return err
}
failed = append(failed, job.ID)
}
for _, id := range failed {
if _, err := client.Jobs.Retry(ctx, id); err != nil {
return err
}
}

The client retries a request only when repeating it is safe:

Failure GET POST, PATCH, DELETE
429 Retried Retried
5xx Retried Returned
Network error or timeout Retried Returned
Other 4xx Returned Returned

A 429 is safe to retry for any method, because the API rejects it before doing any work.

  • Waits back off from 0.5s, doubling up to 8s, each shortened by up to 25% of random jitter. A Retry-After header sets the wait instead. Above 60 seconds, the client returns the error without waiting.
  • A retry that would outlast the context’s deadline is skipped, and the last error is returned.
  • WithRequestTimeout bounds each attempt. A deadline on ctx bounds all attempts together.
  • Redirects are never followed, so a 3xx comes back as an *APIError.
  • A Worker retries its own requests, so WithMaxRequestRetries does not apply to it. Each claim adds the poll wait to WithRequestTimeout.
Error When Check with
*APIError The API answered with a non-2xx status or "success": false errors.AsType[*chronos.APIError](err)
ErrUnauthorized, ErrNotFound, ErrRateLimited An *APIError with status 401, 404 or 429 errors.Is(err, chronos.ErrNotFound)
*NetworkError No usable response: DNS failure, refused or reset connection, timeout errors.AsType[*chronos.NetworkError](err)
ErrTimeout A *NetworkError for an attempt that timed out errors.Is(err, chronos.ErrTimeout)
ErrInvalidResponse A 2xx response without the documented shape, or any response body larger than 64 MiB whatever its status. Resource methods don’t retry it. The worker logs it and retries the claim or result report. errors.Is(err, chronos.ErrInvalidResponse)
ErrInvalidID An empty id, . or .., rejected before any request errors.Is(err, chronos.ErrInvalidID)
ErrInvalidWorker Worker.Run found a setup problem, before any request errors.Is(err, chronos.ErrInvalidWorker)
*WaitTimeoutError Jobs.Wait reached its deadline errors.AsType[*chronos.WaitTimeoutError](err)

*APIError carries StatusCode, Code, Message, RequestID, RetryAfter, RateLimit, FieldErrors and the raw Body. Branch on Code, using the ErrorCode constants. The API can add codes, so keep a default branch. See Error Codes for what each code means.

_, err = client.Schedules.Pause(ctx, scheduleID)
if apiErr, ok := errors.AsType[*chronos.APIError](err); ok && apiErr.Code == chronos.ErrorCodeScheduleAlreadyPaused {
err = nil // already paused
}
if err != nil {
return err
}

An ErrTimeout error also matches context.DeadlineExceeded. Cancelling your own context, or reaching its deadline, returns ctx.Err() instead, so check ctx.Err() to tell the two apart. Jobs.Wait is the exception. At a deadline it returns a *WaitTimeoutError, which also matches context.DeadlineExceeded.

Webhook.Verify checks the signature on push deliveries. Create the verifier with NewWebhook; it needs no client or API key. Pass every active signing secret during a rotation, and a delivery signed with any of them is accepted.

webhook, err := chronos.NewWebhook([]string{os.Getenv("CHRONOS_SIGNING_SECRET")})
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/hooks/chronos", func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
if err != nil {
http.Error(w, "unreadable body", http.StatusBadRequest)
return
}
if err := webhook.Verify(body, r.Header); err != nil {
http.Error(w, "invalid signature", http.StatusUnauthorized)
return
}
if webhook.IsTestRequest(body) {
w.WriteHeader(http.StatusOK)
return
}
var job chronos.PushedJob
if err := json.Unmarshal(body, &job); err != nil {
http.Error(w, "invalid body", http.StatusBadRequest)
return
}
var payload struct {
Report string `json:"report"`
}
if err := json.Unmarshal(job.Payload, &payload); err != nil {
http.Error(w, "invalid payload", http.StatusBadRequest)
return
}
log.Printf("job %s, attempt %d: building %s", job.JobID, job.Attempt, payload.Report)
w.WriteHeader(http.StatusOK)
})

PushedJob is the push delivery body. Its Type is always "job". Payload is the job’s payload as raw JSON, which you decode into your own type. A job without a payload sends JSON null, which decodes to json.RawMessage("null"), not nil.

IsTestRequest(body) reports whether a verified body is a test request, which the dashboard sends from the Test button next to a push URL and from a webhook alert channel’s Send test button. Answer it with a 2xx without running any work. It returns false for a body that is not a JSON object.

Verify checks the X-Chronos-Signature, X-Chronos-Timestamp and X-Chronos-Delivery-Id headers against the raw body. Every failure wraps ErrInvalidWebhook. A timestamp more than 5 minutes from now is rejected. To change the window, pass WithTimestampTolerance(d) to NewWebhook; 0 turns the check off and removes replay protection.

See Signature Verification for the signing scheme.

A Worker claims pull jobs and runs each one in your process, one at a time. Register a handler for each handler name, then call Run, which blocks until its context ends. sendEmail stands in for your own code.

ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
worker := chronos.NewWorker(client)
worker.Handle("send-email", func(ctx context.Context, job *chronos.ClaimedJob) (map[string]any, error) {
var payload struct {
To string `json:"to"`
}
if err := json.Unmarshal(job.Payload, &payload); err != nil {
return nil, err
}
if err := sendEmail(ctx, payload.To); err != nil {
return nil, err
}
return map[string]any{"sent": true}, nil
})
if err := worker.Run(ctx); err != nil {
log.Fatal(err)
}
Option Default Effect
WithPollWait(d) 20s Sets how long each claim waits for a job, in whole seconds up to 20 seconds. 0 claims without waiting, so the worker sends requests continuously while the queue is empty.
WithWorkerID(id) A random id Sets the id the worker registers under, up to 255 characters. Workers sharing an id share one entry in the workers list. Set a stable id in production, because the default adds a new entry on each start.
WithWorkerLogger(l) slog.Default() Sets the logger for worker failures.

Run returns setup problems before it sends a request: an invalid option, a nil client, no handlers, or an invalid, duplicate or nil handler. Those errors match ErrInvalidWorker. Calling Run on a worker that is already running also returns an error, which does not match it. If you pass WithHTTPClient a client with a Timeout, set it above the poll wait, or claims fail while waiting.

Handler does Execution status Chronos retries
Returns a map, or nil for no result completed No
Returns an error, panics, or returns a map that cannot be encoded to JSON failed, with the error’s message cut to 4096 characters While attempts remain
Runs past the job’s timeout timeout While attempts remain

A job can run more than once, so make handlers idempotent. Key on job.JobID, because job.ExecutionID changes on every attempt. job.Payload is the raw JSON, and is null for a job without a payload. job.Schedule is nil for a one-off job.

Pass ctx to everything your handler calls. It ends at the job’s timeout. Go cannot stop a handler that ignores it, so that handler keeps running and holding memory until it returns. The worker reports the timeout at once, then waits up to 30 seconds for the handler to return before its next claim.

When Run’s context ends, the worker abandons the claim in flight, lets a running handler finish within its timeout, reports the result and returns nil. The handler’s ctx does not end on shutdown. Run returns within the job’s timeout plus the time to report the result. If the handler ignores its ctx, Run waits up to 30 more seconds after reporting the timeout, and the handler keeps running after Run returns.

Failure Worker
401 Stops. Run returns the *APIError, which matches ErrUnauthorized.
403 insufficient_scope on a claim or a result Stops. Run returns the *APIError, whose Code is ErrorCodeInsufficientScope. The API key lacks the workers:run scope.
403 credential_not_accepted on a claim or a result Stops. Run returns the *APIError, whose Code is ErrorCodeCredentialNotAccepted. Worker routes accept API keys only.
10 handlers ignored their timeouts and are still running Stops. Run returns ErrTooManyStuckHandlers. Only ending the process frees them, so exit and let your process manager restart it.
403 plan_limit_exceeded on a claim Logs and waits 60 seconds, then claims again.
Any other claim failure Logs and waits 1 second, or the Retry-After value up to 60 seconds, then claims again.
409 on a result Logs and discards the result, because the execution already finished.
Any 4xx on a result other than 408, 409 and 429 Logs and moves on.
Any other failure on a result Sends the result up to 3 times, then logs and moves on.

A result that never reaches the API leaves the execution running until its timeout, and Chronos then retries the job while attempts remain.