Current Location: Home> Latest Articles> Practical Guide to Queue Delayed Tasks and Scheduled Jobs in PHP and MySQL

Practical Guide to Queue Delayed Tasks and Scheduled Jobs in PHP and MySQL

M66 2025-10-05

Introduction

With increasing demands for real-time processing and high concurrency in internet applications, queue delayed tasks and scheduled jobs have become essential tools for system optimization. This article explains how to implement these tasks in PHP and MySQL, providing practical code examples to help developers get started quickly.

Applications of Queue Delayed Tasks

Delayed tasks refer to adding a task to a queue with a specified delay, which is executed after the delay period. They are commonly used for sending SMS verification codes, emails, generating reports, and other tasks that require postponed execution.

In PHP, Redis can be used as a queue service, combined with PHP's Redis extension to implement delayed task management.

Example code:

// Connect to Redis server
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

// Add a task to the queue with a 60-second delay
$job = [
    'to' => 'example@example.com',
    'subject' => 'Test Email',
    'content' => 'Hello, World!'
];
$delay = 60;
$redis->zAdd('delayed_queue', time() + $delay, json_encode($job));

// Fetch and execute tasks whose delay has expired
while (true) {
    $jobs = $redis->zRangeByScore('delayed_queue', 0, time(), ['limit' => [0, 1]]);
    if (!empty($jobs)) {
        $job = array_shift($jobs);
        // Execute task
        sendEmail(json_decode($job, true));
        // Remove executed task from queue
        $redis->zRem('delayed_queue', $job);
    }
    // Sleep 1 second before checking the queue again
    sleep(1);
}

This example demonstrates connecting to Redis, adding a task to a delayed queue, and using a loop to check and execute tasks whose delay time has elapsed.

Applications of Scheduled Jobs

Scheduled jobs execute tasks at predefined intervals, such as daily or hourly. They are commonly used for data backup, log cleanup, and other repetitive operations.

In PHP, cron jobs can be scheduled using the crontab command.

Example code:

// Execute a fixed-time task
function doTask() {
    echo "Fixed time task executed.";
}

// Execute a periodic task
function doPeriodicTask() {
    echo "Periodic task executed.";
}

// Schedule a task to run daily at midnight
$cron = '0 0 * * *';
exec("crontab -l > tmpcron");
file_put_contents("tmpcron", "$cron php -f /path/to/task.php >> /path/to/output.log 2>&1", FILE_APPEND);
exec("crontab tmpcron");

// Schedule a task to run every hour at the 5th minute
$cron = '5 * * * *';
exec("crontab -l > tmpcron");
file_put_contents("tmpcron", "$cron php -f /path/to/task.php >> /path/to/output.log 2>&1", FILE_APPEND);
exec("crontab tmpcron");

// Execute tasks
doTask();
doPeriodicTask();

The code defines fixed-time and periodic tasks and uses crontab to add them to the system's scheduled job list, ensuring automatic execution.

Conclusion

Queue delayed tasks and scheduled jobs in PHP and MySQL can significantly enhance system responsiveness and automation. Delayed tasks are ideal for operations that require deferred execution, while scheduled jobs are suitable for repetitive tasks. The provided code examples help developers quickly implement these features and adapt them to their specific business needs.