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.
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.