gocron
A fluent, in-process Go library for scheduling jobs on cron, interval, and calendar-based rules with built-in distributed coordination.
Repository Health
Technical Analysis
gocron gives Go applications a fluent, code-first API for scheduling recurring work — cron expressions, fixed or random durations, and daily/weekly/monthly calendar rules — without pulling in an external scheduler process. Jobs are built from composable JobDefinition and Task values, so parameters, timeouts, singleton limits, and event listeners are all configured at the call site rather than through a separate config file.
Beyond single-process scheduling, gocron ships first-class support for running multiple instances of the same service: a pluggable DistributedElector interface lets one instance win leadership, and a DistributedLocker interface lets individual job runs be locked across instances, so the same binary can scale horizontally without double-executing scheduled work. Concurrency is bounded per-job (singleton mode) or scheduler-wide (limit mode), and a Monitor/SchedulerMonitor interface exposes execution metrics for wiring into Prometheus or another observability stack.
What You Get
- A
Schedulerinterface withNewJob,Start,Stop, andShutdown/ShutdownWithContextfor full lifecycle control - Seven job types — Duration, DurationRandom, Cron, Daily, Weekly, Monthly, and OneTime — covering most recurring and one-off scheduling needs
- Distributed coordination primitives (
WithDistributedElector,WithDistributedLocker) for running the same scheduler across multiple instances without duplicate execution - Per-job and per-scheduler concurrency controls via singleton mode and limit mode, each with reschedule-or-queue behavior
- An event listener system (
WithEventListeners,WithGlobalJobOptions) plusMonitor/SchedulerMonitorinterfaces for metrics and lifecycle observability - Generated mocks (via gomock) and a
clockwork.FakeClockintegration for deterministic, time-independent unit tests
Common Use Cases
- Running periodic maintenance jobs (cleanup, cache refresh, report generation) inside an existing Go service without a separate cron process
- Coordinating scheduled work across multiple replicas of a horizontally-scaled service using the distributed elector/locker interfaces
- Replacing shell-level cron entries with testable, typed, in-process job definitions that share the app’s logging and error handling
- Rate-limited polling of external APIs using interval-from-completion timing to guarantee rest periods between calls
- Emitting job execution metrics (duration, failures, scheduling delay) to Prometheus or a custom monitor for operational visibility
Under The Hood
Architecture
gocron is organized as three cooperating internal actors behind a public Scheduler interface in scheduler.go: the scheduler goroutine owns job state and processes lookup/update requests over buffered channels (jobOutRequest, jobUpdateNextRuns), the executor (executor.go) receives ready jobs on jobsIn and runs their tasks, reporting completion and rescheduling back over jobsOutCompleted/jobsOutForRescheduling, and job.go defines the internalJob/Job split that separates the mutable scheduling state from the public accessor handed to callers. This channel-based, single-writer design avoids shared-state locking for job data while still allowing safe concurrent Job.NextRun()/RunNow() calls from arbitrary goroutines, bounded by explicit timeouts (defaultRequestJobTimeout, defaultRunNowSendTimeout) so a busy scheduler degrades to ErrSchedulerBusy instead of hanging callers indefinitely.
Tech Stack
The module (github.com/go-co-op/gocron/v2, Go 1.22+) keeps its runtime dependency surface deliberately small: google/uuid for job identifiers, jonboulle/clockwork for an injectable, mockable clock, and robfig/cron/v3 for crontab expression parsing. There is no database, no external broker, and no network layer in the core package — persistence, leader election, and distributed locking are left to pluggable interfaces (DistributedElector, DistributedLocker) that calling code implements against whatever backend (etcd, Redis, a database) it already has.
Code Quality
Testing is extensive: scheduler_test.go and job_test.go alone run to several thousand lines, gomock-generated interfaces live under mocks/, and clockwork.FakeClock is used throughout to make time-based scheduling assertions deterministic rather than flaky. Public errors are all sentinel errors.New values in errors.go with a consistent gocron: <Context>: <problem> naming scheme, which keeps call-site error handling idiomatic (errors.Is). CI runs go_test.yml, a CodeQL scan, and formatting checks on every push, and go vet/goleak guard against goroutine leaks in tests.
What Makes It Unique
Most Go scheduling libraries stop at cron-expression parsing; gocron’s distinguishing feature is treating multi-instance deployment as a first-class concern rather than an afterthought — the elector/locker interfaces let a horizontally-scaled service schedule work exactly once across replicas without requiring gocron itself to ship an opinionated coordination backend. Combined with the SchedulerMonitor event taxonomy (job registered/started/completed/failed, scheduling delay, concurrency-limit-reached), it gives operators enough signal to run scheduled jobs with production-grade observability using only the standard library plus whatever metrics client they already use.
Used by 8 apps in this directory
Cosmos-Server
Security · Authentication
All-in-one self-hosted home server with SmartShield anti-DDoS, Nebula mesh VPN, automatic HTTPS, and a 250-app marketplace — all secured behind a unified auth layer.
ezBookkeeping
Invoicing Finance
Lightweight self-hosted personal finance manager with AI receipt scanning, multi-currency support, and MCP integration for complete data privacy.
Gitea
Devops · Developer Tools · Project Management
Self-hosted DevOps in a single Go binary — Git hosting, GitHub Actions-compatible CI/CD, and 30+ package registries without any SaaS dependency.
Hatchet
AI Development · Developer Tools · Automation
A Postgres-backed orchestration engine for background tasks, AI agents, and durable workflows that replaces Redis queues and multi-datastore durable execution platforms with a single self-hostable service.
Jitsu
Data Engineering
Open-source, fully-scriptable data ingestion engine that streams events from web, apps, and APIs to any data warehouse in real time.
OneUptime
Monitoring
The complete open-source observability platform that replaces PagerDuty, Datadog, Sentry, and StatusPage with a single self-hostable system.
OpenMeter
Invoicing Finance · Developer Tools
Open-source metering and billing engine for AI, agentic, and DevTool monetization — ingest usage events in real time and turn them into accurate invoices automatically.
Stormkit
Devops · Hosting Control Panel
Self-hostable platform for deploying and hosting modern web apps with automated CI/CD, custom domains, and a built-in serverless runtime — a true open-source alternative to Vercel and Netlify.