PHP Task Scheduler: Complete Guide to Cron Jobs and Task Scheduler

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

PHP Task Scheduler: Complete Guide



A Task Scheduler is a critically important tool for any web application running on PHP. It allows you to automate routine operations: sending email newsletters, clearing cache, generating reports, synchronizing data with external APIs, and much more. Unlike manual script execution, a scheduler guarantees timely and reliable task execution without administrator intervention.



Basic Approaches to Implementing a Scheduler in PHP



There are two main ways to implement a task scheduler in PHP projects:



  • System cron (Linux/Unix) — using the built-in cron daemon to call PHP scripts on a schedule.
  • Custom Task Scheduler — implementing scheduling logic directly in PHP code using loops and time checks.


1. System cron with PHP



The most common and performant approach. You create a PHP script that performs the required actions, then add an entry to the server's crontab.



Example PHP script for cron (cron_job.php):



<?php// cron_job.php - clears expired sessionsrequire_once 'config.php';require_once 'db.php';

$stmt = $pdo->prepare("DELETE FROM sessions WHERE last_activity < NOW() - INTERVAL 1 DAY");$stmt->execute();

// Logging executionfile_put_contents('logs/cron.log', date('Y-m-d H:i:s') . " - Sessions cleared", FILE_APPEND);?>


crontab entry (run every hour):



0 * * * * /usr/bin/php /var/www/html/cron_job.php


2. Custom Task Scheduler in PHP



If you don't have access to system cron (e.g., on shared hosting), you can implement a scheduler directly in PHP. This uses a special script that runs on every site visit or via an HTTP request.



Example simple scheduler (task_scheduler.php):



<?phpclass TaskScheduler {    private $tasks = [];    private $lastRunFile = 'last_run.json';

public function addTask($name, callable $callback, $interval) { $this->tasks[] = [ 'name' => $name, 'callback' => $callback, 'interval' => $interval // in seconds ]; }

public function run() { $lastRun = $this->getLastRunTimes();

foreach ($this->tasks as $task) { $lastTime = $lastRun[$task['name']] ?? 0; if (time() - $lastTime >= $task['interval']) { echo "Executing task: {$task['name']}"; call_user_func($task['callback']); $lastRun[$task['name']] = time(); } }

file_put_contents($this->lastRunFile, json_encode($lastRun)); }

private function getLastRunTimes() { if (file_exists($this->lastRunFile)) { return json_decode(file_get_contents($this->lastRunFile), true); } return []; }}

// Usage$scheduler = new TaskScheduler();

$scheduler->addTask('send_newsletter', function() { // Newsletter sending logic echo "Newsletter sent";}, 3600); // Every hour

$scheduler->addTask('clean_cache', function() { // Cache clearing array_map('unlink', glob('cache/*.cache')); echo "Cache cleared";}, 86400); // Once a day

$scheduler->run();?>


3. Advanced Scheduler with CRON Expression Support



For more flexible schedule management, you can implement support for classic cron expressions (minute, hour, day, month, day of week).



Example cron expression parser:



<?phpclass CronPar                    

Recommendations