Nov 17, 20267 min read

How to Add Cron Jobs to a Go net/http App

Run scheduled jobs next to a standard library ServeMux API, such as expiring stock holds and a nightly sales snapshot, with Encore cron jobs, robfig/cron or EventBridge Scheduler.

Illustration for How to Add Cron Jobs to a Go net/http App

The Go standard library will serve POST /holds from an http.ServeMux, and nothing in net/http will call a function every fifteen minutes after the process starts.

That schedule has to live somewhere: in the process, where every replica runs it, or outside it, where a single scheduler should fire once, with idempotent work, retries, and a story for laptops that do not run the job at all.

This guide adds two jobs to a net/http inventory API: expire unpaid stock holds every fifteen minutes, and write a sales snapshot at 02:00 UTC. It starts with Encore, which declares the jobs in Go next to the ServeMux and runs them as platform managed cron in your own AWS or GCP account, then shows robfig/cron in process and EventBridge Scheduler starting an ECS task.

Cron options for a net/http app at a glance

Encorerobfig/cron in processEventBridge Scheduler + ECS
Job declared inGo code (cron.NewJob)Go code started next to the serverTerraform or the AWS console
Runs locallyNocall the private endpoint to testYesinside the processNoinvoke the task by hand
Preview environmentsDoes not runRuns if the preview process starts the schedulerOnly if you create a matching rule
Duplicate runsOne platform managed schedule per jobOnce per replicaOnce per scheduled task, if the task is sized to one
Production runnerEncore platform managed cron in your AWS or GCP accountThe API process itselfEventBridge Scheduler starting an ECS task
IdempotencyStill requiredStill requiredStill required

How do you add cron jobs to net/http with Encore?

Encore

Encore works alongside a plain net/http app: the ServeMux and its handlers stay standard library code, and the scheduled jobs are private endpoints declared with cron.NewJob in the same package. A raw endpoint is an ordinary http.HandlerFunc, so the mux is mounted in one fallback route. Encore cron jobs are platform managed. They do not run during local development or in preview environments, but you can call the private endpoint to test the same code.

A coding agent working in this repository can add the cron.NewJob declarations and the private endpoints in the same change as the hold handlers, then you invoke those endpoints locally to verify the queries before deploying.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create holds-api --example=hello-world$ cd holds-api && mkdir -p holds/migrations

The schema stores a hold that expires if payment never arrives, and a daily snapshot table the nightly job appends to:

-- holds/migrations/1_create_holds.up.sql CREATE TABLE holds ( id TEXT PRIMARY KEY, sku TEXT NOT NULL, qty INT NOT NULL CHECK (qty > 0), status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'paid', 'expired')), expires_at TIMESTAMPTZ NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX holds_active_expiry ON holds (expires_at) WHERE status = 'active'; CREATE TABLE sales_snapshots ( day DATE PRIMARY KEY, paid_qty BIGINT NOT NULL, expired_qty BIGINT NOT NULL, captured_at TIMESTAMPTZ NOT NULL DEFAULT now() );

The Every interval must divide 24 hours evenly; fifteen minutes does. The nightly job uses a cron Schedule in UTC:

// holds/holds.go package holds import ( "context" "encoding/json" "net/http" "strings" "time" "encore.dev/cron" "encore.dev/rlog" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("holds", sqldb.DatabaseConfig{ Migrations: "./migrations", }) //encore:service type Service struct { mux *http.ServeMux } func initService() (*Service, error) { mux := http.NewServeMux() mux.HandleFunc("POST /holds", createHold) mux.HandleFunc("POST /holds/{id}/pay", payHold) return &Service{mux: mux}, nil } //encore:api public raw path=/!fallback func (s *Service) Fallback(w http.ResponseWriter, req *http.Request) { s.mux.ServeHTTP(w, req) } func createHold(w http.ResponseWriter, r *http.Request) { var in struct { ID string `json:"id"` SKU string `json:"sku"` Qty int `json:"qty"` } if err := json.NewDecoder(r.Body).Decode(&in); err != nil || strings.TrimSpace(in.ID) == "" || in.Qty < 1 { http.Error(w, "id, sku and a positive qty are required", http.StatusBadRequest) return } _, err := db.Exec(r.Context(), ` INSERT INTO holds (id, sku, qty, expires_at) VALUES ($1, $2, $3, now() + interval '15 minutes')`, in.ID, in.SKU, in.Qty) if err != nil { http.Error(w, "could not create hold", http.StatusInternalServerError) return } w.WriteHeader(http.StatusCreated) } func payHold(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") res, err := db.Exec(r.Context(), ` UPDATE holds SET status = 'paid' WHERE id = $1 AND status = 'active' AND expires_at > now()`, id) if err != nil { http.Error(w, "could not update hold", http.StatusInternalServerError) return } if res.RowsAffected() == 0 { http.Error(w, "hold missing, already paid or already expired", http.StatusConflict) return } w.WriteHeader(http.StatusNoContent) } // Every fifteen minutes, expire unpaid holds. This job does not run locally // or in preview environments; call ExpireHolds yourself to test it. var _ = cron.NewJob("expire-holds", cron.JobConfig{ Title: "Expire unpaid stock holds", Every: 15 * cron.Minute, Endpoint: ExpireHolds, }) type ExpireResult struct { Expired int `json:"expired"` } //encore:api private func ExpireHolds(ctx context.Context) (*ExpireResult, error) { res, err := db.Exec(ctx, ` UPDATE holds SET status = 'expired' WHERE status = 'active' AND expires_at <= now()`) if err != nil { return nil, err } n := int(res.RowsAffected()) rlog.Info("expired holds", "count", n) return &ExpireResult{Expired: n}, nil } // Every night at 02:00 UTC, write yesterday's paid and expired quantities. var _ = cron.NewJob("sales-snapshot", cron.JobConfig{ Title: "Write the daily sales snapshot", Schedule: "0 2 * * *", Endpoint: WriteSalesSnapshot, }) //encore:api private func WriteSalesSnapshot(ctx context.Context) error { // The date key makes a second run on the same day a no-op. _, err := db.Exec(ctx, ` INSERT INTO sales_snapshots (day, paid_qty, expired_qty) SELECT DATE 'yesterday', COALESCE(SUM(qty) FILTER (WHERE status = 'paid'), 0), COALESCE(SUM(qty) FILTER (WHERE status = 'expired'), 0) FROM holds WHERE created_at >= DATE 'yesterday' AND created_at < DATE 'today' ON CONFLICT (day) DO NOTHING`) if err != nil { return err } rlog.Info("sales snapshot written") return nil }

encore run starts Postgres locally and serves the hold endpoints, but it does not fire the cron jobs. Test them by calling the private endpoint from the local development dashboard. On deploy to your own AWS or GCP account, Encore registers the jobs as platform managed cron and calls the endpoints on the schedule. The endpoints must take no request parameters, and they should be idempotent, as the cron jobs documentation notes they may be invoked more than once under some network conditions.

Best fit: a net/http API that wants scheduled work declared next to the handlers and run as platform managed cron in your own AWS or GCP account.

robfig/cron in the net/http process

robfig/cron can start next to http.ListenAndServe and call the same expire function. Every running replica will do that, so three ECS tasks expire the same rows three times unless the query is exclusive. Use a conditional UPDATE or SKIP LOCKED so extra runs become no-ops, and accept that a deploy or a crash can skip a tick.

c := cron.New() _, err := c.AddFunc("*/15 * * * *", func() { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() if _, err := expireHolds(ctx); err != nil { log.Println("expire holds:", err) } }) if err != nil { log.Fatal(err) } c.Start() defer c.Stop()

Best fit: a single-replica process where a missed or doubled tick is acceptable.

EventBridge Scheduler and an ECS task

EventBridge Scheduler can run a flexible rate or a cron expression in UTC and start an ECS task that only runs the job, then exits. You provision the schedule, the task definition, an IAM role that can start the task, and logging. The job code stays idempotent because a schedule can overlap a slow run, and because a retry after a timeout may execute the work twice.

Best fit: teams that already run ECS and want the scheduler outside the API process, with Terraform or the console owning the schedule.

How to choose

Pick Encore when you want the jobs declared next to the ServeMux, tested by calling the private endpoint, and run as platform managed cron in your own AWS or GCP account. Pick EventBridge Scheduler when the schedule already lives in AWS next to ECS and you want the API binary to stay unaware of it. robfig/cron is enough for a single replica and becomes a source of duplicate work as soon as you scale the API.

The idempotency pattern itself does not depend on the choice: claim rows with a conditional UPDATE or an ON CONFLICT insert, so a second run does not expire or snapshot the same work twice.

Frequently asked questions

How do I run a cron job in a Go net/http app?

The quickest way is robfig/cron started next to http.ListenAndServe, but it runs in every replica, so with three instances the job runs three times. For production, trigger the job from one scheduler outside the process, such as EventBridge Scheduler starting an ECS task, and keep the job idempotent.

How do I add cron jobs to a net/http app with Encore?

Write the job as a private Encore endpoint with the signature func(ctx context.Context) error, declare it with cron.NewJob and either Every or a cron Schedule, and mount the ServeMux in a raw endpoint with path=/!fallback. Encore cron jobs are platform managed: they do not run locally or in preview environments, so call the private endpoint yourself to test. On deploy, Encore calls the endpoint on the schedule in your own AWS or GCP account.

How do I keep a cron job from doing the same work twice?

Claim the work in the database first, with a conditional UPDATE or INSERT that only succeeds for rows that have not been processed, and use SKIP LOCKED if two runs can overlap. If the side effect fails, leave the row unclaimed or roll back so the next run can try again.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders