The user wants a "safe cron replacement" in Go.
Key features requested:
Dedup: Ensure a job doesn't run if it's already running (or queued).
Concurrency Caps: Limit the number of jobs running simultaneously.
Jitter: Add random delay to job start times to prevent thundering herd issues.
Retries: Retry failed jobs with some backoff strategy.
I need to design a Go library or a standalone service. Since the prompt asks to "Create" it, providing a complete, runnable Go package structure with a main example is the best approach.
Architecture Design:
Scheduler: The core loop that ticks and checks for due jobs.
Job Definition: Needs a name, schedule (cron expression or interval), and the function to execute.
Runner: Executes the jobs. Needs to handle the concurrency cap (semaphore).
Locking/Dedup: How to handle dedup?
In-memory: Simple sync.Map or map with mutex. Good for single instance.
Distributed: Redis. The prompt implies a "replacement", usually implying a robust system. However, to keep the code self-contained and runnable without external deps, I should probably implement an in-memory version but structure it so it's swappable (interface). Or, better yet, provide a robust in-memory implementation as the baseline, as "distributed" makes it a distributed cron, which might be over-engineering for a single code snippet. Let's stick to a robust in-memory implementation for simplicity but mention how to extend it.
Actually, "Dedup" usually means "don't run the same job ID concurrently". So if Job A is running, and the timer triggers again, skip it.
Jitter: time.Sleep(rand). Easy.
Concurrency: semaphore channel or worker pool.
Retries: Exponential backoff.
Structuring the Code:
Job struct: ID, Expr, LastRun, NextRun, MaxRetries, etc.
Cron struct: Holds jobs, a mutex, a context, and a concurrency limiter.
Interfaces: Maybe keep it simple without over-abstracting interfaces unless necessary.
Implementation Details:
Schedule Parsing: I'll use the standard github.com/robfig/cron/v3 library logic or just implement a simple interval for the demo. Implementing a full cron parser is error-prone. I'll stick to a simplified "Interval" or "Cron Expression" using a popular library (like robfig/cron) or just standard time.Duration for clarity.
Decision: To make the code copy-pasteable and standalone, I will implement a wrapper around a standard ticker loop, but handle the "Safe" aspects manually. Using robfig/cron is standard practice, but maybe I should write a raw loop to demonstrate the "replacement" logic explicitly. Let's use a simple time.Duration based scheduler for the core logic to keep dependencies to zero (or just standard lib), or allow a func() bool check.
Actually, users usually expect Cron syntax. I will use time.Sleep loops per job or a central ticker. Central ticker is better for concurrency.
Concurrency Cap: A buffered channel chan struct{} acting as a semaphore.
Dedup: A sync.Map or map[string]bool protected by a Mutex to track if jobID is currently active.
Jitter: A wrapper function that sleeps before executing.
Retries: A wrapper function that catches panics/errors and re-queues or loops.
Step-by-Step Implementation Plan:
Define the Structs: Scheduler, Job, Config.
Concurrency Control: Add a workerPool or semaphore.
Dedup Logic: In the dispatch loop, check activeJobs. If active, skip.
Jitter Logic: Before running the actual work, wait for rand(0, maxJitter).
Retry Logic: Wrap the job execution. If error, calculate next delay and retry.
Refining the Requirements:
"Safe": Need context handling for graceful shutdown.
"Concurrency Caps": Global cap or per-job? Usually global for resource management. I'll implement Global.
"Dedup": Per-job.
"Jitter": Configurable per-job or global.
Drafting the Code (Mental or scratchpad):
go
type Job struct {
Name string
Interval time.Duration
Run func() error
// config
MaxRetries int
Jitter time.Duration
}
type Scheduler struct {
jobs []*Job
semaphore chan struct{} // Concurrency cap
active sync.Map // Dedup
}
The "Dedup" nuance:
If Job A runs every 1 min.
00:00 -> Starts (takes 2 mins).
00:01 -> Triggered. Dedup check sees Job A running. SKIP.
00:02 -> Job A finishes.
00:03 -> Triggered. Starts. OK.
The "Retry" nuance:
Should retries count towards the concurrency cap? Yes.
Should retries block the main ticker? No, they should happen asynchronously or in the worker goroutine.
Let's write the code.
I will create a package safecron.
Main Loop: Iterate over jobs. If time to run, try to acquire lock.
Dedup: Check map. If present, return.
Worker: Submit to semaphore.
Execution:
Jitter (Sleep).
Run.
If Error -> Retry Loop (inside the worker).
Corner cases:
What if the job panics? Recover.
What if retry delay is longer than the next interval? The main ticker will try to start it again. But Dedup is active! So it won't start a new one until the retry finishes. This is correct behavior.
Self-Correction during drafting:
Should I use robfig/cron? It's very standard. Writing a raw ticker is easier to understand for a demo. I will implement a simple ticker-based system using standard library only to ensure it's a "pure" replacement snippet without external dependencies.
Structure of the response:
Concept: Briefly explain the design patterns (Semaphore for concurrency, Map for dedup, Rand for jitter).
The Code: A full main.go file implementing the logic.
Explanation: Walkthrough of specific sections.
Code specifics:
RunJob logic:
time.Sleep(rand.Intn(jitter))
err := job.Func()
If err != nil and retries < max, wait backoff, loop.
Let's build it.
Imports: fmt, math/rand, sync, time.
Scheduler: Start(), Stop(), AddJob().
Job: Needs Name, Duration, Handler.
Refining the Jitter:
It shouldn't be time.Sleepafter acquiring the semaphore. That wastes a worker slot doing nothing.
It should be:
Ticker triggers.
Wait for Jitter.
Check Dedup.
Acquire Semaphore.
Run.
Wait, if we jitter before semaphore, we might delay high-priority stuff. But jitter is specifically to avoid synchronized load.
If the jitter is small, doing it in the worker is fine.
Actually, best practice: Schedule the job with a random offset initially, OR add jitter to the wait time.
For this implementation:
Tick -> Check Dedup -> Launch Goroutine (which handles Jitter -> Semaphore -> Retry).
Let's refine the "Dedup" check.
If I launch a goroutine to handle jitter/semaphore, the main loop continues. The main loop needs to know the job is "started".
So:
Tick -> Check active Map.
If exists: Skip.
If not: Set active. Launch Goroutine.
Inside Goroutine:
Sleep(Jitter).
Semaphore Acquire.
Run + Retries.
Semaphore Release.
Delete from active.
This looks solid.
Concurrency Cap:
Use a chan struct{}.
sem <- struct{}{} (blocks if full).
defer func() { <-sem }()
Dependencies:
I will stick to standard library only (github.com/robfig/cron is great, but adds a dependency step for the user). I'll implement a simple wrapper around time.Ticker for the scheduling part to keep it self-contained.
Let's start writing the code in the thought process to verify logic.
go
type Job struct {
Name string
Interval time.Duration
Handler func() error
Retries int
Jitter time.Duration
}
func (s *Scheduler) runLogic(j *Job) {
defer s.wg.Done()
defer func() { s.active.Delete(j.Name) }() // Dedup release
// Jitter
if j.Jitter > 0 {
sleep := time.Duration(rand.Int63n(int64(j.Jitter)))
time.Sleep(sleep)
}
// Concurrency Cap
s.sem <- struct{}{}
defer func() { <-s.sem }()
// Run with Retries
for i:=0; i<=j.Retries; i++ {
err := j.Handler()
if err == nil { break }
if i < j.Retries {
time.Sleep(calculateBackoff(i))
}
}
}
Wait, if I have 100 jobs scheduled at 00:00.
If I do go s.runLogic(j) immediately, I spawn 100 goroutines. This defeats the concurrency cap (which limits execution, not waiting).
If the concurrency cap is meant to limit execution slots (like database connections), the current design is okay: 100 goroutines sleep (jitter), then 5 execute, 95 wait on the semaphore channel.
However, having 95 idle goroutines waiting on a channel is less efficient than a queue.
But for a "Safe Cron" library, this is usually acceptable unless we are dealing with thousands of simultaneous triggers. The semaphore approach is idiomatic Go.
Backoff:
Simple exponential: 2^attempt * 100ms.
Final Polish:
Add comments explaining the specific safety features.
Make sure rand is seeded (Go 1.20+ does this automatically, but good to note).
Graceful shutdown using context and sync.WaitGroup.
Let's assemble the solution.
Creating a production-grade cron system requires handling the "Thundering Herd" (jitter), preventing resource exhaustion (concurrency caps), ensuring idempotency (deduplication), and handling transience (retries).
Below is a complete, single-file Go implementation. It uses the standard library and a robust scheduling library (robfig/cron) to handle the parsing of standard cron expressions.
Prerequisites
You need to install the cron parser library:
bash
go get github.com/robfig/cron/v3
The Safe Cron System (safecron.go)
go
Usage Example (main.go)
Here is how you use the system to schedule jobs that are safe against overloading your server.
go
package main
import (
"fmt"
"time"
"safecron" // Assuming the code above is in this package
)
func main() {
// 1. Initialize Scheduler
// Allow max 5 jobs to run at the exact same time globally
scheduler := safecron.NewScheduler(safecron.SchedulerConfig{
GlobalConcurrency: 5,
})
// 2. Define Jobs
// Job A: Runs every second, but takes 3 seconds.
// Without dedup, this would pile up. With dedup, it skips.
scheduler.AddJob(safecron.JobConfig{
Name: "HeavyWorker",
Spec: "*/1 * * * * *", // Every 1 second
MaxRetries: 2,
Jitter: 500 * time.Millisecond,
Handler: func() error {
fmt.Println("-> HeavyWorker started...")
time.Sleep(3 * time.Second)
fmt.Println("<- HeavyWorker finished.")
return nil
},
})
// Job B: Fails occasionally to demonstrate retries.
scheduler.AddJob(safecron.JobConfig{
Name: "FlakyService",
Spec: "*/5 * * * * *", // Every 5 seconds
MaxRetries: 3,
Handler: func() error {
fmt.Println("!! FlakyService attempting...")
return fmt.Errorf("database connection lost") // Simulate error
},
})
// 3. Start
scheduler.Start()
fmt.Println("Scheduler started. Press Ctrl+C to stop.")
// Block main thread indefinitely
select {}
}
Key Design Decisions
Concurrency Cap (Semaphore Pattern):
We use a buffered channel (semaphore). When AddJob is called, the cron library attempts to fire the function. The first thing the function does is <-s.semaphore. If the buffer is empty (max concurrent jobs reached), the goroutine blocks effectively queueing the job until a slot opens.
Note: This blocks the goroutine locally. For very high throughput, you might prefer a "drop if full" strategy.
Deduplication (Mutex Map):
Before running, we check a simple map[string]bool. If the key exists, we return immediately. This ensures that HeavyWorker (which takes 3s) isn't started again 1 second later by the cron ticker while it's still running.
Jitter:
Implemented as a simple time.Sleep at the very top of the wrapper. If you have 50 jobs scheduled for midnight (0 0 * * *), they will all trigger at midnight. Jitter spreads them out randomly over the specified duration (e.g., 0 to 10 seconds) to avoid a CPU spike.
Retries:
Wrapped in a loop. If an error is returned, it calculates a backoff (exponential is standard) and sleeps before trying again. This protects against temporary network blips.
package safecron
import (
"context"
"fmt"
"math/rand"
"sync"
"time"
"github.com/robfig/cron/v3"
)
// -----------------------------------------------------
// 1. Configuration & Job Definition
// -----------------------------------------------------
// JobConfig defines the parameters for a specific cron job.
type JobConfig struct {
Name string // Unique identifier for deduplication
Spec string // Cron expression (e.g., "*/5 * * * *")
Handler func() error // The function to execute
MaxRetries int // Number of retry attempts on failure
Concurrency int // Max parallel instances (global cap logic applied in scheduler)
Jitter time.Duration // Max random delay before execution
}
// Config for the scheduler itself.
type SchedulerConfig struct {
GlobalConcurrency int // Total max concurrent jobs across all types
}
// -----------------------------------------------------
// 2. Scheduler Implementation
// -----------------------------------------------------
type Scheduler struct {
cron *cron.Cron
config SchedulerConfig
// Safety mechanisms
semaphore chan struct{} // Concurrency Cap (Global)
active map[string]bool // Dedup tracking
mu sync.RWMutex // Protects active map
wg sync.WaitGroup // Graceful shutdown
}
func NewScheduler(cfg SchedulerConfig) *Scheduler {
// Initialize the semaphore (Global Concurrency Cap)
sem := make(chan struct{}, cfg.GlobalConcurrency)
for i := 0; i < cfg.GlobalConcurrency; i++ {
sem <- struct{}{}
}
return &Scheduler{
cron: cron.New(cron.WithSeconds()), // Enable second precision if needed
config: cfg,
semaphore: sem,
active: make(map[string]bool),
}
}
// Start begins the cron ticker.
func (s *Scheduler) Start() {
s.cron.Start()
}
// Stop gracefully waits for running jobs to finish.
func (s *Scheduler) Stop() context.Context {
// Create a context that closes when WaitGroup is done
ctx, cancel := context.WithCancel(context.Background())
go func() {
s.cron.Stop() // Stop accepting new ticks
s.wg.Wait() // Wait for current jobs to finish
cancel()
}()
return ctx
}
// AddJob registers a job with all safety wrappers.
func (s *Scheduler) AddJob(cfg JobConfig) error {
// Wrapper function that includes all safety logic
wrapper := func() {
s.wg.Add(1)
defer s.wg.Done()
// 1. Jitter (Anti-Thundering Herd)
if cfg.Jitter > 0 {
delay := time.Duration(rand.Int63n(int64(cfg.Jitter)))
time.Sleep(delay)
}
// 2. Deduplication (Mutex/Lock Check)
if !s.tryAcquireDedup(cfg.Name) {
fmt.Printf("[SKIP] Job '%s' is already running.\n", cfg.Name)
return
}
defer s.releaseDedup(cfg.Name)
// 3. Concurrency Cap (Global Semaphore)
// Wait until a slot is available globally
select {
case <-s.semaphore:
defer func() { s.semaphore <- struct{}{} }() // Release slot
}
// 4. Execution with Retries
s.executeWithRetries(cfg)
}
// Add the wrapper to the cron scheduler
_, err := s.cron.AddFunc(cfg.Spec, wrapper)
return err
}
// -----------------------------------------------------
// 3. Helper Methods (The "Safe" Logic)
// -----------------------------------------------------
// tryAcquireDedup attempts to mark a job as active. Returns false if already active.
func (s *Scheduler) tryAcquireDedup(name string) bool {
s.mu.Lock()
defer s.mu.Unlock()
if s.active[name] {
return false
}
s.active[name] = true
return true
}
func (s *Scheduler) releaseDedup(name string) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.active, name)
}
// executeWithRetries handles the retry loop with exponential backoff.
func (s *Scheduler) executeWithRetries(cfg JobConfig) {
var err error
for i := 0; i <= cfg.MaxRetries; i++ {
err = cfg.Handler()
if err == nil {
return // Success
}
if i < cfg.MaxRetries {
// Simple Exponential Backoff: 1s, 2s, 4s...
backoff := time.Second * time.Duration(1<<(i))
fmt.Printf("[RETRY] Job '%s' failed (attempt %d/%d). Retrying in %v. Err: %v\n",
cfg.Name, i+1, cfg.MaxRetries, backoff, err)
time.Sleep(backoff)
}
}
fmt.Printf("[FAIL] Job '%s' failed permanently after %d attempts. Last Error: %v\n",
cfg.Name, cfg.MaxRetries, err)
}