Overview
This tutorial shows you how to build scheduled tasks using Motia’s cron triggers. You’ll create a system that runs periodic maintenance jobs, generates reports, and cleans up old data automatically. What you’ll learn:- Using cron triggers for scheduled execution
- Cron expression syntax
- Periodic data processing
- Scheduled maintenance tasks
- Cleanup jobs
- Report generation
Prerequisites
Before starting, make sure you have:
- Node.js version 19 or higher
- Completed the Hello World tutorial
- Basic understanding of cron expressions
Use Case: Automated Maintenance System
We’ll build a system that:- Cleans up expired sessions every hour
- Generates daily reports at midnight
- Monitors system health every 5 minutes
- Archives old data weekly
- Sends summary notifications
Project Setup
Cron Expression Quick Reference
*/5 * * * * *- Every 5 seconds0 */5 * * * *- Every 5 minutes0 0 * * * *- Every hour0 0 0 * * *- Daily at midnight0 0 0 * * 0- Weekly on Sunday at midnight0 0 0 1 * *- Monthly on the 1st at midnight
Building the System
Step 1: Session Cleanup (Hourly)
Createsteps/maintenance/cleanup-sessions.step.ts:
steps/maintenance/cleanup-sessions.step.ts
- Cron trigger: Automatically executes on schedule
- No input: Cron-triggered Steps don’t receive input data
- Enqueue reports: Sends results to notification system
- Error handling: Logs failures for monitoring
Step 2: Daily Report Generation
Createsteps/maintenance/generate-daily-report.step.ts:
steps/maintenance/generate-daily-report.step.ts
Step 3: Health Monitor (Every 5 Minutes)
Createsteps/maintenance/health-check.step.ts:
steps/maintenance/health-check.step.ts
Step 4: Weekly Data Archival
Createsteps/maintenance/archive-old-data.step.ts:
steps/maintenance/archive-old-data.step.ts
Step 5: Notification Handlers
Createsteps/maintenance/send-reports.step.ts:
steps/maintenance/send-reports.step.ts
Step 6: Manual Trigger API
Createsteps/maintenance/trigger-job.step.ts:
steps/maintenance/trigger-job.step.ts
Running the Application
Testing Cron Jobs
Create Test Data
Createscripts/seed-data.ts:
scripts/seed-data.ts
Development Tips
- Use shorter intervals: Test with seconds instead of hours
- Add logging: Include detailed logs to track execution
- Manual triggers: Create HTTP endpoints to run jobs on demand
- Monitor execution: Watch logs and state changes
Production Considerations
Add Execution Locking
Common Schedules
| Task | Expression | Description |
|---|---|---|
| Every minute | 0 * * * * * | Testing/monitoring |
| Every 5 minutes | 0 */5 * * * * | Health checks |
| Hourly | 0 0 * * * * | Cleanup jobs |
| Daily at 2 AM | 0 0 2 * * * | Reports |
| Weekly (Sunday) | 0 0 0 * * 0 | Archival |
| Monthly (1st) | 0 0 0 1 * * | Billing |
| Weekdays at 9 AM | 0 0 9 * * 1-5 | Business hours |
Next Steps
Background Jobs
Handle failures in scheduled jobs
Observability
Track job execution and performance
State Management
Advanced state operations
Production Deploy
Deploy your scheduled tasks