scheduler
The scheduler package provides periodic task execution at fixed intervals.
Core Components:
Scheduler: Executes a runner at configured intervals. ImplementsRunnerinterface so it can be used as anapplicationservice.New(period, runner): Creates a new scheduler with the specified interval and runner.
Full package docs at pkg.go.dev
Step-by-step guide
Section titled “Step-by-step guide”-
Create a task function
func scheduledTask(ctx context.Context) error {log.InfoContext(ctx, "scheduled task executed")return nil}The function receives a context with a unique trace ID for each execution.
-
Create a scheduler
s := scheduler.New(time.Second, application.RunnerFunc(scheduledTask))First argument is the interval between executions. Second is any
application.Runnerimplementation. Useapplication.RunnerFuncto wrap a function. -
Run the scheduler
err := s.Run(ctx)The scheduler blocks and executes the task at each interval until the context is cancelled.
Expected output:
time=2025-01-01T12:00:01.000+00:00 level=INFO msg="scheduler task started" traceID=abc-123time=2025-01-01T12:00:01.000+00:00 level=INFO msg="scheduled task executed" traceID=abc-123time=2025-01-01T12:00:01.000+00:00 level=INFO msg="scheduler task finished" traceID=abc-123time=2025-01-01T12:00:02.000+00:00 level=INFO msg="scheduler task started" traceID=def-456time=2025-01-01T12:00:02.000+00:00 level=INFO msg="scheduled task executed" traceID=def-456time=2025-01-01T12:00:02.000+00:00 level=INFO msg="scheduler task finished" traceID=def-456 -
Handle errors
func scheduledTask(ctx context.Context) error {if err := doWork(); err != nil {return err // Logged automatically, scheduler continues}return nil}Errors returned from the task are logged but do not stop the scheduler. The next execution proceeds as normal.
Using with Application
Section titled “Using with Application”Since Scheduler implements the Runner interface, it can be registered as a service in an Application:
app := application.New()
s := scheduler.New(time.Minute, application.RunnerFunc(scheduledTask))
app.RegisterService("scheduler", s)
app.Run(ctx)The scheduler starts when the application runs and stops when the application shuts down.
Complete example
Section titled “Complete example”package main
import ( "context" "time"
"github.com/platforma-dev/platforma/application" "github.com/platforma-dev/platforma/log" "github.com/platforma-dev/platforma/scheduler")
func scheduledTask(ctx context.Context) error { log.InfoContext(ctx, "scheduled task executed") return nil}
func main() { ctx, cancel := context.WithCancel(context.Background())
s := scheduler.New(time.Second, application.RunnerFunc(scheduledTask))
go func() { time.Sleep(3500 * time.Millisecond) cancel() }()
s.Run(ctx)}