> ## Documentation Index
> Fetch the complete documentation index at: https://docs.reliantlabs.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Add a Go cron job or background worker to a Forge service

> Scaffold a Go cron job worker that fires each tick on one replica, run it locally, and ship it hosted inside your API workload with no extra infrastructure.

You will add `digest`, a scheduled job that counts the active products in `shop` once a minute, and watch it run locally and on Reliant hosting. The worker runs inside your existing `server` process, so a schedule needs no new process, queue or Kubernetes object, and it claims each tick in your app's Postgres, so each tick fires on one replica. `reliant forge agent skill load workers` is the full reference.

## Before you begin

* The `shop` project from [Build a Go and React app with Connect RPC](https://docs.reliantlabs.io/guides/forge/build-go-react-app-connect-rpc.md). Any Forge project with `db/migrations` works.
* Forge v1.6 or later. Inside Reliant, run it as `reliant forge`, and check the version with `reliant forge --version` inside the project.
* No account for the local steps. The hosted step needs a Reliant organization with [hosting billing](https://docs.reliantlabs.io/hosting/overview.md).

**1. Scaffold the cron worker**

`--schedule` takes a five-field cron expression. Every minute is useful for trying it out:

```bash terminal theme={null}
reliant forge scaffold worker digest --kind cron --schedule "* * * * *"
```

```text Output (trimmed) theme={null}
✅ Worker 'digest' added successfully!
  • worker 'digest' joins the composition graph on `forge generate`: `shop server` runs it (internal/app/graph_gen.go)
   - deploy/kcl/workloads.k (worker 'digest' runs in the binary's `server` root — it has no subcommand of its own; nothing to declare)
   - deploy/kcl/prod/main.k (worker 'digest' runs in _api, the binary's `server`; nothing to bind)
```

It wrote `internal/workers/digest/worker.go` and `worker_test.go`, and added a `newDigest` constructor to `internal/app/compose.go`, which hands the worker its logger, config and database. No deploy file changed. Without `--kind cron` you get a plain long-running worker instead: a `Start` loop on a 30-second ticker for you to replace with a queue or event stream. A plain worker runs on every replica; wrap it in a `pkg/lease` singleton if only one may run at a time.

**2. Read the schedule**

The schedule is a constant in the worker. That constant is the only place it is declared, and `generate` reads it back from there:

```go internal/workers/digest/worker.go theme={null}
// Schedule is the cron expression that controls how often Run executes.
const Schedule = "* * * * *"

// PerReplica is false: each tick runs on exactly one replica, however many
// the workload scales to.
const PerReplica = false

func (w *Worker) Start(ctx context.Context) error {
	return cronkit.Run(ctx, cronkit.Options{
		Name:       w.Name(),
		Schedule:   Schedule,
		PerReplica: PerReplica,
		Claims:     cronkit.Postgres(w.deps.DB),
		Logger:     w.deps.Logger,
	}, w.Run)
}
```

Before a tick runs, `cronkit.Postgres` inserts the worker name and the tick's scheduled time into `forge_cron_ticks`. The replica whose insert succeeds runs the tick; the others skip it. Set `PerReplica = true` only for work every pod must do.

**3. Write the tick**

`Run` is one tick. Pass `ctx` to every call so shutdown cancels it. A returned error is logged and the schedule carries on:

```go internal/workers/digest/worker.go theme={null}
func (w *Worker) Run(ctx context.Context) error {
	if w.deps.DB == nil {
		return nil
	}
	at, _ := cronkit.TickTime(ctx)
	n, err := db.CountProduct(ctx, w.deps.DB, orm.WhereEq("active", true))
	if err != nil {
		return err
	}
	w.deps.Logger.InfoContext(ctx, "digest", "tick", at, "active_products", n)
	return nil
}
```

`cronkit.TickTime` is the scheduled time, the same on every replica: a good key for an idempotent write. `DB` is an optional dependency, hence the nil check.

**4. Run the scaffolded test**

```bash terminal theme={null}
go build ./... && task test:short -- -v ./internal/workers/digest/...
```

```text theme={null}
--- PASS: TestCronWorkerStartStop (0.05s)
--- PASS: TestCronWorkerName (0.00s)
--- PASS: TestCronWorkerRunAcceptsContext (0.00s)
ok  	example.com/shop/internal/workers/digest	0.062s
```

The start-and-stop test builds the worker with no database, so it logs `cron worker started WITHOUT tick claims`. That warning is expected here.

**5. Watch it tick locally**

Start the stack with `reliant forge env up dev`, then read the API log. The worker runs inside the `api` process:

```bash terminal theme={null}
grep '"msg":"digest"' .forge/logs/dev/api.log
```

```text Output (trimmed) theme={null}
{"time":"2026-11-20T10:38:00.001Z","level":"INFO","msg":"digest",...,"tick":"2026-11-20T10:38:00Z","active_products":12,...}
{"time":"2026-11-20T10:39:00.007Z","level":"INFO","msg":"digest",...,"tick":"2026-11-20T10:39:00Z","active_products":11,...}
```

The count dropped after a product was archived between the two ticks. The claims are rows you can query:

```bash terminal theme={null}
reliant forge db query dev "select * from forge_cron_ticks order by 2 desc limit 3"
```

```text theme={null}
job     tick                    claimed_by  claimed_at
digest  2026-11-20 10:39:00+00  build-box   2026-11-20 10:39:00.005313+00
digest  2026-11-20 10:38:00+00  build-box   2026-11-20 10:38:00.000443+00
digest  2026-11-20 10:37:00+00  build-box   2026-11-20 10:37:00.006307+00
```

cronkit creates this table on first use and prunes rows older than a day. Stop the stack with `reliant forge env down dev`.

**6. Check what production deploys**

```bash terminal theme={null}
reliant forge env render prod --list
```

```text theme={null}
CLUSTER  KIND             NAMESPACE  NAME     APP
hosted   Workload         -          migrate  -
hosted   Workload         -          api      -
hosted   StaticSite       -          web      -
hosted   ManagedDatabase  -          shop     -
```

The list is the same as before the worker existed: `digest` ships inside the `api` workload, which is why it can run on Reliant hosting.

**7. Deploy it and see the ticks hosted**

Build a release and promote it, as in [Deploy a Go API with managed Postgres](https://docs.reliantlabs.io/guides/hosting/deploy-go-api-managed-postgres.md):

```bash terminal theme={null}
reliant forge env build prod --release v0.1.0
reliant forge env deploy prod v0.1.0 --yes
reliant forge obs logs prod "cron" --limit 3
```

```text theme={null}
11:07:00.006  INFO      api      cron job executing
11:06:00.005  INFO      api      cron job executing
11:05:00.005  INFO      api      cron job executing
```

This sandbox project kept the scaffold's default `Run`, which logs `cron job executing`. The hosted database holds the claims, so the boot log has no `WITHOUT tick claims` warning.

**8. Set the real schedule**

Change the constant, for example to `const Schedule = "0 8 * * *"` for 08:00 every day, and redeploy. The worker's name is its claim key, so renaming the worker starts a fresh claim history.

## What this does not do

* **No hosted cron-kind workloads.** A workload declared with `kind = "cron"` in `deploy/kcl` becomes a Kubernetes CronJob, and Reliant hosting does not run those yet. Binding one to `forge.OnHosted` fails the render with `cron is not available on hosted until metering covers it`. Bind it to a cluster you run, or use a cron worker as in this guide, which runs hosted.
* **No catch-up.** Each tick runs at most once. If the replica that claimed a tick crashes mid-run, that tick is lost, and ticks missed while the app was down are not replayed.
* **No overlap guard across replicas.** Ticks on one replica never overlap, but a slow tick on one replica can still be running when the next tick starts on another. If `Run` must never overlap itself, hold a `pkg/lease` lease inside it (`reliant forge project libraries lease`).
* **No database, no claims.** Without a database every replica fires every tick, and the worker logs a warning at start.

## Troubleshooting

> [accordion] cron worker started WITHOUT tick claims: every replica fires every tick
>
> The worker got no database: the project has no `db/migrations`, or the process started without `DATABASE_URL`. Give it one, or set `PerReplica = true` if every replica should run each tick.

> [accordion] workload 'digest' cannot run on the hosted runtime: schedule: cron is not available on hosted until metering covers it
>
> A `kind = "cron"` workload is bound to `forge.OnHosted` in an env's `main.k`. Remove that workload and use the scaffolded cron worker, or bind the workload to a cluster you run.

## Next steps

> [card] [Add a custom RPC](https://docs.reliantlabs.io/guides/forge/add-custom-rpc.md)
>
> Write a Connect RPC handler and call it through a typed hook

> [card] [Add a table](https://docs.reliantlabs.io/guides/forge/add-table-crud-api-pages.md)
>
> Generate the CRUD API and pages for a new entity

> [card] [Deploy a Go API](https://docs.reliantlabs.io/guides/hosting/deploy-go-api-managed-postgres.md)
>
> Ship the API, its workers and Postgres to Reliant hosting

> [card] [Hosting overview](https://docs.reliantlabs.io/hosting/overview.md)
>
> What hosting runs, and what it does not run yet


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.