Lesson 36 • Advanced
Cron Jobs & Task Scheduling ⏰
Automate recurring tasks with cron expressions, build a PHP task scheduler, and manage background workers with Supervisor.
What You'll Learn in This Lesson
- • Read and write cron expressions for any schedule
- • Build a PHP task scheduler with error handling
- • Set up Linux crontab for automated PHP scripts
- • Manage long-running worker processes with Supervisor
- • Monitor worker pools and handle graceful shutdowns
Cron Syntax & Task Scheduling
Cron uses a five-field expression to define schedules: minute, hour, day of month, month, and day of week. An asterisk (*) means "every," and */5 means "every 5." Combine these to create any schedule from "every minute" to "first Monday of January at 3:15 AM."
Try It: Cron & Task Scheduler
Parse cron expressions and build a task scheduler with error handling
// Cron Jobs: Automating Recurring Tasks
console.log("=== Understanding Cron Syntax ===");
console.log();
console.log(" ┌───── minute (0-59)");
console.log(" │ ┌───── hour (0-23)");
console.log(" │ │ ┌───── day of month (1-31)");
console.log(" │ │ │ ┌───── month (1-12)");
console.log(" │ │ │ │ ┌───── day of week (0-7, 0=Sun)");
console.log(" │ │ │ │ │");
console.log(" * * * * * command");
console.log();
// Cron expression parser
class CronParser {
constructor(expression, description)
...Background Workers
For tasks that need to run continuously (not just on a schedule), use long-running PHP worker processes. Supervisor ensures workers restart automatically if they crash, and pcntl_signal() enables graceful shutdown when deploying new code.
Try It: Worker Processes
Manage a pool of 4 workers with Supervisor and monitor their status
// Background Workers & Process Management
console.log("=== PHP Worker Process Pattern ===");
console.log();
console.log(" // worker.php — Long-running background process");
console.log(" #!/usr/bin/env php");
console.log(" <?php");
console.log(" declare(ticks=1);");
console.log(" pcntl_signal(SIGTERM, function() {");
console.log(" echo 'Shutting down gracefully...';");
console.log(" exit(0);");
console.log(" });");
console.log();
console.log(" while (true) {");
console.log("
...⚠️ Common Mistakes
flock -n /tmp/backup.lock php backup.php>> /var/log/cron.log 2>&1). Without it, debugging failures is impossible.$schedule->command('emails:send')->dailyAt('08:00')📋 Quick Reference — Cron & Workers
| Concept | Description |
|---|---|
| crontab -e | Edit cron schedule for current user |
| flock | Prevent overlapping cron executions |
| Supervisor | Process manager for long-running workers |
| pcntl_signal() | Handle Unix signals for graceful shutdown |
| 2>&1 | Redirect stderr to stdout for logging |
🎉 Lesson Complete!
You can now automate PHP tasks! Next, learn to manage environment configuration and secrets securely.
Sign up for free to track which lessons you've completed and get learning reminders.