Scheduling Tasks in PHP

by | Oct 19, 2022

In the scenario where you want to execute tasks repeatedly at a specific time and have full control over when they are executed and how the results are handled, it makes sense to build this into your application instead of setting up a cron job, for example. I’d like to give you a quick example of how you can achieve this in PHP using two great libraries, ReactPHP and cron-expression. ReactPHP is an event-driven programming library that has an event loop at its core. cron-expression understands CRON expressions, can determine if they are due to be executed and calculate the next execution date of the expression. The following is a simple example of scheduling tasks based on these two libraries:

<?php

namespace Icinga\Blog;

use Cron\CronExpression;
use DateTime;
use React\EventLoop\Loop;

/**
 * Schedule the given task based on the specified CRON expression
 *
 * @param callable $task
 * @param CronExpression $cron
 */
function schedule(callable $task, CronExpression $cron): void
{
    $now = new DateTime();
    // CRON is due, run task asap:
    if ($cron->isDue($now)) {
        Loop::futureTick(function () use ($task) {
            $task();
        });
    }

    // Function that executes the task
    // and adds a timer to the event loop to execute the function again when the task is next due:
    $schedule = function () use (&$schedule, $task, $cron) {
        $task();

        $now = new DateTime();
        $nextDue = $cron->getNextRunDate($now);
        Loop::addTimer($nextDue->getTimestamp() - $now->getTimestamp(), $schedule);
    };

    // Add a timer to the event loop to execute the task when it is next due:
    $nextDue = $cron->getNextRunDate($now);
    Loop::addTimer($nextDue->getTimestamp() - $now->getTimestamp(), $schedule);
}

// Run example task every minute:
$cron = new CronExpression('* * * * *');
$task = function () {
    echo date('Y-m-d H:i:s') . ": Task running\n";
};
schedule($task, $cron);

 

You May Also Like…

Native Binaries with PHP

Native Binaries with PHP

There is always a big debate about whether interpreted or compiled languages are more useful. I think it is important...

Subscribe to our Newsletter

A monthly digest of the latest Icinga news, releases, articles and community topics.