📋 Table of Contents
🎯 Giới Thiệu
Cron là gì?
Cron = Công cụ schedule tasks (jobs) chạy tự động theo lịch trên server.
Use cases:
node-cron là gì?
node-cron = JavaScript library để tạo cron jobs trong Node.js
So với Linux crontab:
🧠 Khái Niệm Cơ Bản
1. Cron Syntax
Ví dụ:
2. Process vs Thread
Process = 1 chương trình đang chạy độc lập
Đặc điểm:
Mỗi process có memory riêng Chạy độc lập, không ảnh hưởng nhau Crash 1 process ≠ crash tất cả Có PID riêng (Process ID) 🔰 PHASE 1: Simple Cron (Console Log)
Mục tiêu: Hiểu cơ bản về cron
Step 1: Install
Step 2: Tạo Simple Worker
File: workers/simpleWorker.js
Step 3: Test
Output:
✅ Success! Bạn đã tạo cron job đầu tiên!
Press Ctrl+C để stop.
Step 4: Multiple Schedules
📝 PHASE 2: Database Integration
Mục tiêu: Ghi logs vào MySQL database
Step 1: Setup Database (ví dụ Sequelize)
Step 2: Tạo DB Worker
Step 3: Test DB Worker
Terminal 1: Run worker
Output:
Terminal 2: Check database
Result:
✅ Success! Worker đang ghi vào database!
🚀 PHASE 3: Production Worker
Mục tiêu: Tạo real-world email worker với error handling, retry logic
Architecture:
Step 1: Database Schema
Table: job_queue
Step 2: Email Worker
File: workers/emailWorker.js
Express vs Worker Processes
Khái Niệm Cốt Lõi
Express App và Worker là 2 Node.js processes RIÊNG BIỆT:
Comparison Table
Đặc điểm:
✅ Chạy liên tục background ✅ Có cron job (node-cron) ✅ Process scheduled tasks ❌ KHÔNG handle HTTP request Communication Flow
Key Points:
Express và Worker KHÔNG nói chuyện trực tiếp Giao tiếp qua MySQL database Express write vào database Decoupled architecture = Reliable & Scalable PM2 Ecosystem Management
PM2 là gì?
PM2 = Process Manager for Node.js
Chức năng:
Start/stop/restart processes Monitor processes (CPU, memory) Auto-start on server boot Installation
Basic Commands
Ecosystem Config File
File: ecosystem.config.js (project root)
Usage with Ecosystem
Auto-Start on Server Boot
Test:
Log Management
Setup log rotation:
Result:
Logs > 10MB → auto-rotate 🐛 Troubleshooting
Issue 1: Cron Not Running
Symptoms:
Worker starts but no logs Debug:
Solution:
Ensure worker is running: pm2 status Issue 2: Jobs Stuck in Processing
Symptoms:
Jobs have status = 'processing' Debug:
Solution:
Issue 3: Memory Leak
Symptoms:
Worker memory increases over time PM2 restarts worker frequently Debug:
Solution:
Issue 4: Multiple Workers Running
Symptoms:
Debug:
Solution:
Issue 5: PM2 Not Auto-Starting on Boot
Symptoms:
After server reboot, workers not running Debug:
Solution:
🎓 Summary
Key Takeaways:
node-cron = Schedule jobs in Node.js Cron syntax: * * * * * = Every minute Separate processes: Express ≠ Worker Communication: Via database (MySQL) PM2: Manage multiple processes ecosystem.config.js: Define all processes Graceful shutdown: Handle SIGTERM/SIGINT Error handling: Try-catch, retry logic Monitoring: PM2 logs, metrics, alerts Production: Auto-start, auto-restart, log rotation Learning Path: