Scheduled Jobs

Provides a scheduled job engine and UI based on gocron

Technology

A Project Forge module that provides a scheduled job engine and web UI based on gocron.

Overview

The schedule module enables applications to run jobs on a schedule using cron expressions or intervals. It provides:

Features

Job Management

Monitoring & Debugging

Integration

Usage

Basic Setup

The schedule service is automatically initialized and started when the module is included:

1
2
// Service is available in app.State
jobs := as.Services.Schedule.ListJobs()

Creating Jobs

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Define a job function
jobFunc := func(ctx context.Context, logger util.Logger) (any, error) {
logger.Info("executing my job")
// Perform work here
return "job completed", nil
}

// Schedule the job
job, err := as.Services.Schedule.NewJob(
ctx,
"daily-cleanup", // job name
gocron.DailyAt("02:00"), // schedule (cron or interval)
jobFunc, // function to execute
true, // singleton mode
logger, // logger instance
"maintenance", "cleanup", // tags
)

Schedule Types

The module supports various schedule types through gocron:

1
2
3
4
5
6
7
// Cron expressions
gocron.CronJob("0 2 * * *", false) // Daily at 2 AM

// Intervals
gocron.DurationJob(time.Hour) // Every hour
gocron.DailyAt("15:30") // Daily at 3:30 PM
gocron.WeeklyOn(time.Monday, "09:00") // Weekly on Monday at 9 AM

Job Function Pattern

Job functions should follow this signature:

 1
2
3
4
5
6
7
8
9
10
11
12
13
type JobFunc func(ctx context.Context, logger util.Logger) (any, error)

func myJob(ctx context.Context, logger util.Logger) (any, error) {
// Use the provided context for cancellation
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
// Perform work
result := doWork()
return result, nil
}
}

Accessing Job Information

 1
2
3
4
5
6
7
8
9
10
11
// List all jobs
jobs := as.Services.Schedule.ListJobs()

// Get specific job
job := as.Services.Schedule.GetJob(jobID)

// Check execution counts
count := as.Services.Schedule.ExecCounts[jobID]

// Get last result
result := as.Services.Schedule.Results[jobID]

Web Interface

The module provides admin pages for job monitoring:

The interface shows: - Job ID, name, and tags - Last and next execution times
- Total execution count - Latest execution result and any errors

Configuration

Environment Variables

as.Services.Schedule.EnableLogging(false) // Disable debug logs

Service Options

When creating jobs, you can specify: - Singleton mode: Prevents overlapping executions - Tags: For categorization and filtering - Custom names: For easier identification in logs and UI

Implementation Details

Components

Thread Safety

The service uses mutexes to ensure thread-safe access to: - Execution counts map - Results storage - Job state information

Error Handling

Source Code