Background Jobs (Cron)
The Background Jobs component provides a standardized way to schedule and manage recurring tasks in your ServerCN application using node-cron.
Background jobs are essential for tasks like:
- Generating and sending daily reports.
- Cleaning up temporary files or expired sessions.
- Synchronizing data with third-party APIs.
- Sending scheduled notifications or emails.
Installation Guide
Install the component using the ServerCN CLI:
npx servercn-cli add background-jobsThis will install node-cron and its types, and create the basic jobs structure in your project.
Project Structure
Depending on your architecture, the jobs are organized as follows:
- MVC:
src/jobs/ - Feature:
src/shared/jobs/
Implementation
1. Define a Job
Create individual job files for different tasks to keep your code modular and readable.
File: src/jobs/example.job.ts
2. Initialize Jobs
Export a central initialization function to start all your jobs at once.
File: src/jobs/index.ts
3. Usage in Server
Import and call the initJobs function in your main entry file (usually server.ts).
Cron Syntax Refresher
Real-World Examples
Here are some common scenarios where background jobs are used in production-grade Express applications.
1. Expired Refresh Tokens Cleanup
src/cron/cleanup-refresh-tokens.cron.ts or src/jobs/cleanup-refresh-tokens.job.ts
2. Daily Database Cleanup
Remove unverified users who haven't verified their email within 24 hours.
3. System Health Heartbeat
Send a heartbeat or log system performance metrics every 15 minutes.
4. Syncing Exchange Rates
Fetch and cache currency exchange rates from an external API every hour.
Best Practices
1. Error Handling
Always wrap your job logic in try-catch blocks to prevent an error in one job from crashing your entire Node.js process.
2. Logging
Use a proper logger (like Winston or Pino) inside your jobs to track execution history and troubleshoot failures.
3. Resource Management
If a job performs heavy database operations, ensure it doesn't block the main event loop. Consider offloading very large tasks to a separate worker process or a dedicated queue system (like BullMQ) if needed.
4. Idempotency
Ensure your jobs are idempotent—running the same job twice (due to a restart or overlap) should not cause data corruption or duplicate side effects.
Summary
The Background Jobs component using node-cron is a powerful and lightweight solution for adding scheduled tasks to your ServerCN application without the complexity of a full-blown message queue.