Overview
Cron jobs in EverShop:- Run automatically on a schedule you define
- Use cron syntax for flexible scheduling
- Execute in the background without blocking the application
- Are registered in bootstrap.ts during application startup
- Support async/await for modern JavaScript patterns
How Cron Jobs Work
- Extension’s
bootstrap.tsregisters cron jobs - Jobs are scheduled using cron expressions
- Jobs execute automatically at specified times
- Output is logged to console
Directory Structure
Cron jobs are organized in thecrons folder:
Creating Your First Cron Job
Real-World Example
Here’s the actual example from the sample extension:The Cron Function
extensions/sample/src/crons/everyMinute.ts
The Bootstrap Registration
extensions/sample/src/bootstrap.ts
Cron Schedule Syntax
Cron jobs use standard cron syntax with 5 fields:Common Schedules
Advanced Examples
Daily Database Cleanup
src/crons/dailyCleanup.ts
src/bootstrap.ts
Weekly Sales Report
src/crons/weeklySalesReport.ts
src/bootstrap.ts
Inventory Sync
src/crons/syncInventory.ts
src/bootstrap.ts
Abandoned Cart Recovery
src/crons/abandonedCartReminder.ts
src/bootstrap.ts
Registration Options
TheregisterJob function accepts these options:
Dynamic Enable/Disable
Use environment variables to control jobs:Multiple Cron Jobs
Register multiple jobs in the same bootstrap:src/bootstrap.ts
Best Practices
- Logging - Log start, success, and failure of each job
- Error Handling - Use try-catch to handle errors gracefully
- Idempotency - Design jobs to be safe to run multiple times
- Timeouts - Set reasonable timeouts for external API calls
- Performance - Optimize queries and batch operations
- Monitoring - Track job execution and failures
- Testing - Test jobs in development before production
Testing Cron Jobs
Manual Execution
Create a test script to run jobs manually:scripts/testCron.ts
Development Testing
Use a short interval for testing:Troubleshooting
Job Not Running
- Verify job is registered in
bootstrap.ts - Check
enabledis set totrue - Verify cron expression syntax
- Check application is running:
npm run dev - Look for errors in console logs
Job Running Multiple Times
- Ensure job name is unique
- Check you’re not registering the same job twice
- Verify only one instance of the app is running
Job Errors
- Add try-catch blocks
- Check database connections
- Verify external API credentials
- Test the job function in isolation
Common Use Cases
Maintenance Tasks
- Database cleanup
- Log rotation
- Cache invalidation
- Session cleanup
Data Synchronization
- Inventory updates
- Price synchronization
- Product imports
- Order exports
Reporting
- Daily sales reports
- Weekly analytics
- Monthly summaries
- Performance metrics
Customer Engagement
- Abandoned cart emails
- Re-engagement campaigns
- Birthday emails
- Product recommendations
Next Steps
Event Subscribers
React to real-time events
Creating Extensions
Learn extension architecture