> For the complete documentation index, see [llms.txt](https://0xgosu.gitbook.io/monolith-framework/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://0xgosu.gitbook.io/monolith-framework/examples/cron-scheduler.md).

# Cron Scheduler

Demonstrates **cron-scheduled services** — the framework's 5th service type — backed by the embedded NATS JetStream message scheduler (nats-server v2.14+, ADR-51).

A module registers a single cron service with `RegisterCronService`. The schedule is registered **server-side**, so in a multi-node deployment exactly one message fires per occurrence (no client-side ticker, no leader election). Each occurrence is delivered to the handler through a durable pull consumer with explicit acknowledgement.

```go
func (m *HeartbeatModule) RegisterServices(c mono.ServiceContainer) error {
    return c.RegisterCronService("emit", mono.CronServiceConfig{
        Schedule: "@every 2s",
        Payload:  []byte(`{"event":"heartbeat"}`),
    }, func(ctx context.Context, msg *mono.Msg) error {
        // ... do periodic work ...
        return nil // framework Acks on nil, Naks on error
    })
}
```

## Key points

* **Requires JetStream**: enable it via `WithJetStreamStorageDir(...)`. Registering a cron service without JetStream fails fast at startup.
* **Schedule formats**: a cron expression in the standard five-field format (`"0 0 * * *"` = daily at midnight) or the six-field seconds-first format (`"0 0 0 * * *"`; five-field expressions are normalized by prepending a `"0"` seconds field), a named alias (`"@daily"`, `"@hourly"`, …), or an interval (`"@every 5m"`, minimum 1s). A `TimeZone` may only be used with cron expressions (not `@every`).
* **Acknowledgement is framework-owned**: return `nil` to Ack the occurrence, or a non-nil error to Nak it (redelivered up to the consumer's `MaxDeliver`). Do **not** call `msg.Ack()` yourself.
* **Idempotent**: the schedule is (re)published on every startup, so changing the `Schedule`, `Payload`, `TimeZone`, or `TTL` and redeploying overwrites the live schedule in place.
* **Retiring a cron service**: set `Deprecated: true` and deploy to purge the schedule (keeping the code), then remove the `RegisterCronService` call in a later release.

## Run

```bash
make run-example-4
# or
cd examples/cron-scheduler && go run .
```

You should see a heartbeat printed every 2 seconds, then a clean shutdown on Ctrl+C.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://0xgosu.gitbook.io/monolith-framework/examples/cron-scheduler.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
