Overview
Thescheduler.Scheduler executes an application.Runner according to a cron schedule. It provides:
- Standard 5-field cron syntax
- Named schedules (
@daily,@hourly, etc.) - Interval syntax (
@every 30m) - Automatic validation at construction time
- Context-aware execution with trace IDs
Creating a Scheduler
Create a scheduler with a cron expression and a runner:Cron Expression Syntax
Standard 5-Field Format
Standard cron uses 5 fields:Examples
Named Schedules
Use predefined schedule names:@yearlyor@annually- Run once a year at midnight on January 1st (0 0 1 1 *)@monthly- Run once a month at midnight on the first day (0 0 1 * *)@weekly- Run once a week at midnight on Sunday (0 0 * * 0)@dailyor@midnight- Run once a day at midnight (0 0 * * *)@hourly- Run once an hour at the start of the hour (0 * * * *)
Interval Syntax
Use@every for simple intervals:
Running the Scheduler
Start the scheduler withRun(ctx):
- Starts the cron scheduler
- Blocks until the context is cancelled
- Stops the scheduler gracefully
- Returns when all tasks complete
Task Execution
Each scheduled execution:- Gets a new context with a unique trace ID
- Logs start and completion
- Logs errors but continues running
- Maintains the original parent context
Implementing a Runner
Your task must implement theapplication.Runner interface:
Complete Example
1
Create a runner
Implement the task logic:
2
Create the scheduler
Configure the schedule:
3
Register with application
Add to your application’s runners:
Multiple Schedulers
Create multiple schedulers for different tasks:Time Zone
Schedulers use UTC by default. All cron expressions are evaluated in UTC:Error Handling
Errors from the runner are logged but don’t stop the scheduler:Best Practices
Validate early
The constructor validates cron expressions at creation time, so invalid schedules fail fast during application startup.
Use named schedules
Prefer
@daily over 0 0 * * * for better readability and intent.Make tasks idempotent
Tasks may run multiple times if the application restarts. Ensure they’re safe to re-run.
Monitor task duration
Log start and end times to track how long tasks take and detect slowdowns.