Generating Tasks
The fastest way to create a new scheduled task is using the Kit CLI:- Create
src/tasks/cleanup_logs_task.rswith a task stub - Create
src/tasks/mod.rsif it doesn’t exist - Create
src/schedule.rsfor registering tasks - Create
src/bin/schedule.rsscheduler binary
Defining Schedules
Kit supports two approaches for defining scheduled tasks:1. Trait-Based Tasks (Recommended)
For complex tasks that need dependencies or reusable logic, implement theTask trait and configure the schedule during registration:
src/schedule.rs:
2. Closure-Based Tasks
For quick, inline tasks without separate files:Registering Tasks
Register your tasks insrc/schedule.rs:
Schedule Frequency Options
Kit provides a fluent API for defining when tasks should run:Common Intervals
| Method | Description |
|---|---|
.every_minute() | Run every minute |
.every_five_minutes() | Run every 5 minutes |
.every_ten_minutes() | Run every 10 minutes |
.every_fifteen_minutes() | Run every 15 minutes |
.every_thirty_minutes() | Run every 30 minutes |
.hourly() | Run every hour at minute 0 |
.hourly_at(30) | Run every hour at minute 30 |
.daily() | Run daily at midnight |
.daily_at("03:00") | Run daily at 3:00 AM |
.weekly() | Run weekly on Sunday at midnight |
.monthly() | Run monthly on the 1st at midnight |
Day-Specific Schedules
Time Modifiers
Chain.at() with any schedule to set a specific time:
Custom Cron Expressions
For full control, use cron syntax:Task Configuration
Preventing Overlapping
Prevent a task from running if a previous instance is still executing:Running in Background
Run tasks without waiting for completion:Running the Scheduler
Kit provides CLI commands for running scheduled tasks:Run Once
Execute all due tasks once (typically called by cron every minute):Daemon Mode
Run continuously, checking for due tasks every minute:List Tasks
Display all registered scheduled tasks:Run Specific Task
Run a specific task by name:Production Setup
Using Cron
Add a single cron entry to run the scheduler every minute:Using Systemd
Create a systemd service for the scheduler daemon:Accessing App Context
Scheduled tasks have full access to the application context, just like controllers:File Organization
The recommended file structure for scheduled tasks:Summary
| Feature | Usage |
|---|---|
| Create task | kit make:task TaskName |
| Trait-based | Implement Task trait, configure schedule during registration |
| Closure-based | schedule.call(|| async { ... }) |
| Register tasks | schedule.add(schedule.task(...).daily().name("...")) |
| Run once | kit schedule:run |
| Run daemon | kit schedule:work |
| List tasks | kit schedule:list |
| Prevent overlap | .without_overlapping() |
| Background | .run_in_background() |