Documentation menu

Application services

Scheduler

The scheduler runs recurring tasks (a nightly cleanup, an hourly sync, a daily report) from one cron entry. You list the tasks in app/Console/Kernel.php; cron starts php taphra schedule:run every minute, and it runs the tasks that are due at that minute.

Defining tasks

#

app/Console/Kernel.php is a PHP file of Schedule:: calls (or a Kernel class, below). A task is either a console command or a PHP callable, followed by a frequency:

app/Console/Kernel.php
<?php
// app/Console/Kernel.php
use Taphra\Schedule;

// A console command, run as `php taphra cache:clear` in a child process.
Schedule::command('cache:clear')->daily()->at('03:30');

// A callable, run inside the schedule:run process.
Schedule::call(function (): void {
    file_put_contents(APP_TMP_PATH . '/scheduler-heartbeat.txt', date('c'));
})->everyMinute();

// Any cron expression: minute 15 of every sixth hour.
Schedule::command('cache:clear')->cron('15 */6 * * *');

The file may also declare a Kernel class and define the tasks in its schedule() method, which schedule:run and schedule:list call. The class lives in the app's namespace (App\Console\Kernel, or APP_NAMESPACE\Console\Kernel when the app sets another one; a global Kernel in an app whose APP_NAMESPACE is ''). schedule() may be static or not, and when it takes a parameter it gets the Taphra\Schedule instance:

PHP
<?php
// app/Console/Kernel.php
namespace App\Console;

use Taphra\Schedule;

class Kernel
{
    public static function schedule(): void
    {
        Schedule::command('cache:clear')->daily()->at('03:30');
    }
}

schedule:list and schedule:run both load the file, so both see the tasks. Command tasks can name your own console commands (see cli.md) with their arguments, as in Schedule::command('reports:send --period=week').

Frequencies

#
Method Cron expression Runs
everyMinute() * * * * * every minute
everyFiveMinutes() */5 * * * * at minutes 0, 5, 10 ...
everyTenMinutes() */10 * * * * at minutes 0, 10, 20 ...
hourly() 0 * * * * at minute 0 of every hour
daily() 0 0 * * * at midnight
weekdays() 0 0 * * 1-5 at midnight, Monday to Friday
weekends() 0 0 * * 6,0 at midnight, Saturday and Sunday
weekly() 0 0 * * 0 at midnight on Sunday
monthly() 0 0 1 * * at midnight on the first of the month
cron('m h dom mon dow') as given as given

at('HH:MM') sets the hour and the minute of the expression, so it belongs after daily(), weekdays(), weekends(), weekly() and monthly(): weekly()->at('07:05') is 5 7 * * 0. Call it after the frequency, since a frequency method replaces the whole expression. On hourly() it would also fix the hour and turn the task into a daily one.

cron() takes a standard five-field expression (minute, hour, day of month, month, day of week) with lists, ranges and steps over * or a range: */15 * * * *, 1-10/2 * * * *, 5,10-20/5 * * * *, 0 9 * * MON-FRI. Steps count from the start of the range, as in cron (*/2 in the day-of-month field is the 1st, 3rd, 5th and so on). When both day fields are restricted, a day matches if either one does. A malformed expression throws InvalidArgumentException when the task is defined.

Times are read in PHP's default time zone (date.timezone in the CLI's php.ini), which may differ from the web server's.

Running the scheduler

#

Add one crontab entry on one server:

Shell
* * * * * cd /var/www/myapp && APP_ENV=prod php taphra schedule:run >> /dev/null 2>&1

Each run checks every task against the current minute and runs the due ones, one after another, then exits. It prints a line per task and a summary, or No scheduled tasks were due.

php taphra schedule:list shows the tasks and their cron expressions:

Text
+--------------------+--------------+----------------------+
| Command / Callback | Expression   | Next Run             |
+--------------------+--------------+----------------------+
| cache:clear        | 30 3 * * *   | (cron: 30 3 * * *)   |
| [callable]         | * * * * *    | (cron: * * * * *)    |
| cache:clear        | 15 */6 * * * | (cron: 15 */6 * * *) |
+--------------------+--------------+----------------------+

The "Next Run" column repeats the expression; it does not compute a date.

In a test, or to run the due tasks from your own code, call the scheduler directly:

PHP
use Taphra\Schedule;

$ran = Schedule::getInstance()->runDue();   // the number of tasks that ran

Testing your tasks

#

Schedule::command() and Schedule::call() add to one schedule for the whole PHP process, and a test run is one process. Schedule::reset() forgets that schedule, so the next call starts an empty one. Call it in setUp() and tearDown(): each test then starts without the tasks of the tests before it and leaves none behind.

PHP
<?php
// test/ScheduleTest.php
use PHPUnit\Framework\TestCase;
use Taphra\Schedule;

class ScheduleTest extends TestCase
{
    protected function setUp(): void
    {
        Schedule::reset();
    }

    protected function tearDown(): void
    {
        Schedule::reset();
    }

    public function testTheKernelSchedulesTheNightlyCleanup(): void
    {
        $schedule = Schedule::getInstance();
        $schedule->loadKernel();   // runs App\Console\Kernel::schedule()

        $this->assertSame(
            [['name' => 'cache:clear', 'expression' => '30 3 * * *', 'next' => '(cron: 30 3 * * *)']],
            $schedule->getTasks()
        );
    }

    public function testACallbackTaskRuns(): void
    {
        $ran = false;
        Schedule::call(function () use (&$ran): void { $ran = true; })->everyMinute();

        $this->assertSame(1, Schedule::getInstance()->runDue());
        $this->assertTrue($ran);
    }
}

The first test uses the Kernel class form of app/Console/Kernel.php above: after a reset, loadKernel() (which runDue() also calls) runs its schedule() again. A plain file of Schedule:: calls is included once per process, so its tasks are not defined again after a reset; test such tasks by calling the code that defines them, as the second test does. A module that defines its tasks in a method of its own, schedule(Schedule $schedule), is tested the same way: reset, call schedule(Schedule::getInstance()), then read getTasks().

Long tasks and overlapping runs

#

The scheduler does not check whether the previous run of a task is still going. A task that can take longer than its interval should take a lock, so that a second copy started by the next cron minute steps aside:

app/Lib/FeedSync.php
<?php
// app/Lib/FeedSync.php
namespace App\Lib;

use Taphra\Lock\Lock;

final class FeedSync
{
    public static function run(): string
    {
        if (!Lock::getLock('feed-sync')) {
            return 'skipped: the previous sync is still running';
        }
        try {
            // ... fetch and store the feed ...
            return 'synced';
        } finally {
            Lock::releaseLock('feed-sync');
        }
    }
}
PHP
// in app/Console/Kernel.php
Schedule::call(fn () => \App\Lib\FeedSync::run())->everyFiveMinutes();

Tasks of one run also wait for each other, so a slow callable delays the tasks after it. Put long work in a console command (it runs in its own process) or push it to a queue from a short task.

A task that throws, or a command that exits with a non-zero code, is logged as an error with the category Schedule; the other due tasks still run, and schedule:run lists the failed tasks at the end and exits with 1.