Cron Scheduler
Grit uses the asynq Scheduler for cron-like recurring task execution. Schedule periodic cleanup jobs, report generation, or any recurring work using standard cron expressions. Tasks are enqueued into the same Redis-backed job queue used by background jobs.
How It Works
The cron scheduler is a separate component from the job worker. While the worker processes jobs from the queue, the scheduler periodically enqueues new tasks according to cron expressions. Both share the same Redis connection and task types.
┌────────────────────┐ ┌─────────┐ ┌──────────────────┐│ Cron Scheduler │ │ Redis │ │ Worker ││ │ │ Queue │ │ ││ Every hour: │ │ │ │ ││ enqueue │────>│ task │────>│ handleTokens ││ tokens:cleanup │ │ │ │ Cleanup() ││ │ │ │ │ ││ Custom schedule: │ │ │ │ ││ enqueue │────>│ task │────>│ handleCustom() ││ report:generate │ │ │ │ │└────────────────────┘ └─────────┘ └──────────────────┘
Scheduler Service
The scheduler lives at internal/cron/cron.go. It wraps the asynq Scheduler and registers cron tasks at creation time.
// Task represents a registered cron task for display purposes.type Task struct {Name string `json:"name"`Schedule string `json:"schedule"`Type string `json:"type"`}// RegisteredTasks holds the list of cron tasks for the admin API.var RegisteredTasks []Task// Scheduler wraps asynq.Scheduler for cron-like job scheduling.type Scheduler struct {scheduler *asynq.Scheduler}// New creates a new cron Scheduler connected to Redis.func New(redisURL string) (*Scheduler, error)// Start begins executing scheduled tasks (runs in a goroutine).func (s *Scheduler) Start() error// Stop shuts down the scheduler gracefully.func (s *Scheduler) Stop()
Built-in Tasks
Grit ships with three built-in cron tasks — expired-token cleanup (hourly), orphan-upload cleanup (daily), and a weekly full-database backup. They're registered before the // grit:cron-tasks marker, so your own tasks slot in right after them.
| Task | Schedule | Type | Description |
|---|---|---|---|
| Cleanup expired tokens | 0 * * * * | tokens:cleanup | Every hour, on the hour |
| Cleanup orphan uploads | 15 3 * * * | uploads:cleanup_orphans | Daily at 03:15 (low traffic) |
| Weekly database backup | 0 2 * * 0 | backup:weekly | Sunday 02:00 UTC |
func New(redisURL string) (*Scheduler, error) {redisOpt, err := asynq.ParseRedisURI(redisURL)if err != nil {return nil, fmt.Errorf("parsing redis URL for cron: %w", err)}scheduler := asynq.NewScheduler(redisOpt, nil)// Register built-in cron tasksRegisteredTasks = []Task{}// Cleanup expired tokens -- every hour_, err = scheduler.Register("0 * * * *", asynq.NewTask("tokens:cleanup", nil))if err != nil {return nil, fmt.Errorf("registering tokens cleanup: %w", err)}RegisteredTasks = append(RegisteredTasks, Task{Name: "Cleanup expired tokens",Schedule: "0 * * * *",Type: "tokens:cleanup",})// Cleanup orphan uploads -- daily at 03:15_, err = scheduler.Register("15 3 * * *", asynq.NewTask("uploads:cleanup_orphans", nil))if err != nil {return nil, fmt.Errorf("registering orphan upload cleanup: %w", err)}RegisteredTasks = append(RegisteredTasks, Task{Name: "Cleanup orphan uploads", Schedule: "15 3 * * *", Type: "uploads:cleanup_orphans",})// Weekly full-database backup -- Sunday 02:00 UTC_, err = scheduler.Register("0 2 * * 0", asynq.NewTask("backup:weekly", nil))if err != nil {return nil, fmt.Errorf("registering weekly backup: %w", err)}RegisteredTasks = append(RegisteredTasks, Task{Name: "Weekly database backup", Schedule: "0 2 * * 0", Type: "backup:weekly",})// grit:cron-tasksreturn &Scheduler{scheduler: scheduler}, nil}
Adding Custom Cron Tasks
Add custom cron tasks by registering them in the New() function. Use standard cron expressions (5-field format). The task must have a corresponding handler registered in the job worker.
// Add after the "// grit:cron-tasks" marker:// Generate daily reports -- every day at midnight_, err = scheduler.Register("0 0 * * *", asynq.NewTask("report:daily", nil))if err != nil {return nil, fmt.Errorf("registering daily report: %w", err)}RegisteredTasks = append(RegisteredTasks, Task{Name: "Generate daily reports",Schedule: "0 0 * * *",Type: "report:daily",})// Send weekly digest -- every Monday at 9 AMpayload, _ := json.Marshal(map[string]string{"type": "weekly"})_, err = scheduler.Register("0 9 * * 1", asynq.NewTask("email:digest", payload))if err != nil {return nil, fmt.Errorf("registering weekly digest: %w", err)}RegisteredTasks = append(RegisteredTasks, Task{Name: "Send weekly digest",Schedule: "0 9 * * 1",Type: "email:digest",})
Cron Expression Reference
| Expression | Schedule |
|---|---|
| * * * * * | Every minute |
| 0 * * * * | Every hour |
| 0 0 * * * | Every day at midnight |
| 0 9 * * 1 | Every Monday at 9 AM |
| */5 * * * * | Every 5 minutes |
| 0 0 1 * * | First day of every month |
The grit:cron-tasks Marker
The // grit:cron-tasks comment in cron.go is a marker used by the code generator. grit generate job NightlyReport --cron "30 23 * * *" writes the job, registers its handler with the worker, and injects the schedule at this marker, where it also joins the list on the admin Cron page. You can add tasks manually either above or below it -- just do not remove the marker.
// ... built-in tasks above ...// grit:cron-tasks <-- CLI injects new tasks herereturn &Scheduler{scheduler: scheduler}, nil}
Admin Cron Viewer
The admin panel shows all registered cron tasks via the GET /api/admin/cron/tasks endpoint. This endpoint reads from the RegisteredTasks slice, which is populated during scheduler initialization.
// CronHandler handles admin cron task endpoints.type CronHandler struct{}// ListTasks returns all registered cron tasks.func (h *CronHandler) ListTasks(c *gin.Context) {tasks := cron.RegisteredTasksif tasks == nil {tasks = []cron.Task{}}c.JSON(http.StatusOK, gin.H{"data": tasks,})}// Response example:// {// "data": [// {// "name": "Cleanup expired tokens",// "schedule": "0 * * * *",// "type": "tokens:cleanup"// }// ]// }
Lifecycle
The scheduler is started in main.go after the worker, and stopped during graceful shutdown. It runs as a goroutine alongside the HTTP server.
// Create and start the cron schedulercronScheduler, err := cron.New(cfg.RedisURL)if err != nil {log.Printf("Warning: Cron scheduler failed to start: %v", err)} else {cronScheduler.Start()defer cronScheduler.Stop()log.Println("Cron scheduler started")}
A sweep over every tenant, sent once
Most scheduled work in a real app is a sweep: go through the records, find the ones that need something, tell somebody. Two things in that sentence are easy to get wrong, and a project reported writing a 278-line billing file to get both right. Each is one call now.
func billingSweep(ctx context.Context, db *gorm.DB) error {return tenant.ForEach(ctx, db, func(ctx context.Context, orgID string) error {var overdue []models.Invoiceif err := db.WithContext(ctx).Where("status = ? AND due_at < ?", "sent", time.Now()).Find(&overdue).Error; err != nil {return err}for _, invoice := range overdue {err := notify.Once(ctx, db, "invoice-overdue:"+invoice.ID, func() error {return mailer.Send(ctx, invoice.Email, overdueTemplate(invoice))})if err != nil {return err}}return nil})}
tenant.ForEach runs the work once per active organization with that organization set on the context it hands you, so the query inside is scoped without a WHERE clause of your own. Pass that context down: a query made with the outer one is either unscoped or refused. It comes from the multitenant plugin, and one organization's failure does not stop the others. The errors come back joined, each naming the organization it came from, because a sweep that returns at the first error leaves everybody after it unprocessed and the symptom is one customer whose invoices stopped arriving.
notify.Once runs its function at most once, ever, for the key you give it. The invoice stays overdue and the sweep runs every few minutes, so without a record of having sent it the customer is emailed on every run. Called again with the same key it does nothing and returns no error: "already sent" is the outcome you wanted.
Three things about it worth knowing before you rely on it. The claim is written to notification_claims before the work runs and removed if the work fails, so two replicas running the same sweep a second apart cannot both send, and a failed send is retried on the next run. A process that dies between claiming and sending loses that one notification, which is the deliberate trade against sending it every thirty seconds. And in a multitenant project the key is claimed per organization automatically, because a global claim would mean the first organization swept claims invoice-overdue:42 and nobody else is ever told about their own invoice 42.
Nothing deletes a claim on a schedule, and that is on purpose: deleting one makes its notification sendable again, so a retention sweep over that table would re-send everything older than the window. A row is about a hundred bytes. To release one deliberately there is notify.Forget, and to show "reminder sent" on a screen without claiming anything there is notify.Sent.
