RapidGo
No results found

Scheduler

Cron-based task scheduling with structured logging and panic recovery.

The scheduler lets you define recurring tasks using cron expressions, with automatic logging and panic recovery.

Configuration

Register scheduled tasks in app/schedule/schedule.go:

package schedule

import (
    "context"
    "github.com/RAiWorks/RapidGo/v2/core/app"
    "github.com/RAiWorks/RapidGo/v2/core/scheduler"
)

func RegisterSchedule(s *scheduler.Scheduler, a *app.App) {
    // Run every minute
    s.Add("* * * * *", "cleanup-temp-files", func(ctx context.Context) error {
        // Clean up temporary files...
        return nil
    })

    // Run daily at midnight
    s.Add("0 0 * * *", "daily-report", func(ctx context.Context) error {
        // Generate and send daily report...
        return nil
    })

    // Run every 5 minutes
    s.Add("*/5 * * * *", "sync-data", func(ctx context.Context) error {
        // Sync external data...
        return nil
    })
}

Cron Expression Format

Standard 5-field cron plus descriptors:

┌───────────── minute (0-59)
│ ┌───────────── hour (0-23)
│ │ ┌───────────── day of month (1-31)
│ │ │ ┌───────────── month (1-12)
│ │ │ │ ┌───────────── day of week (0-6, Sun=0)
│ │ │ │ │
* * * * *

Descriptors

Descriptor Equivalent
@yearly 0 0 1 1 *
@monthly 0 0 1 * *
@weekly 0 0 * * 0
@daily 0 0 * * *
@hourly 0 * * * *
@every 5m Every 5 minutes
@every 1h30m Every 1.5 hours

Running the Scheduler

go run cmd/main.go schedule:run

This starts the cron engine and blocks until the process is stopped. On shutdown, it waits for any running tasks to complete.

Scheduler API

s := scheduler.New(logger)

// Add a task
s.Add("*/5 * * * *", "my-task", func(ctx context.Context) error {
    return nil
})

// List registered tasks
for _, task := range s.Tasks() {
    fmt.Printf("%s: %s\n", task.Name, task.Schedule)
}

// Run (blocks until ctx is cancelled)
s.Run(ctx)

Features

  • Structured logging for task start, completion, and failure with duration
  • Automatic panic recovery — panics are logged with stack traces, not crashes
  • Graceful shutdown — waits for running tasks to finish
  • Uses robfig/cron under the hood