Luminova Framework

PHP Luminova: Cron Task Scheduling & Execution

Last updated: 2026-11-28 20:57:12

Register recurring tasks and configure their execution intervals, callbacks, and output.

The TaskScheduler class is the central configuration for defining and scheduling tasks executed by the cron task manager. It extends the AbstractTaskScheduler class provided by Luminova Core and allows you to register services and set how often each one runs.

Tasks are defined by implementing the schedule method, to register task's controller class and method


Class Definition


Methods

onCreate

The onCreate method is an optional initialization hook called during the scheduler's construction, before default configuration values are assigned. Override this method to customize the scheduler configuration, including the lock directory and filename. Use app.timezone for the default timezone or timezone() for a specific task.

protected function onCreate(): void

Example

protected function onCreate(): void
{
    self::$lockPath = 'path/to/cron/';
    self::$filename = 'schedules.json';
}

Note:Properties not explicitly configured in onCreate retain their default values.


schedule

Defines the scheduled tasks to be executed by the scheduler.

The schedule abstract method is the primary method where tasks are defined.Call service once per task, then chain the configuration methods that apply to it.

abstract protected function schedule(): void

Responsibilities

  • Register the services to be executed by cron.
  • Set the execution interval for each service.
  • Optionally set logging, output, callbacks, and ping URLs.

Example Implementation

protected function schedule(): void
{
    $this->service(ServiceOneCommand::class, 'fooMethod')
        ->seconds(5)
        ->output(root('/writeable/log/cron/', 'output.log'));

    $this->service(ServiceTwoCommand::class, 'barMethod')
        ->minutes(10)
        ->log('info');
}

Configuration Options

All configuration methods are chained after service and apply to the service registered immediately before them.

service

The service method registers the task to be executed.

Use a routable CLI controller or Novakit console class with a public method.

protected final function service(string $class, string $method): self

Parameters:

ParameterTypeDescription
$classclass-string<AbstractController>&#124;class-string<AbstractConsole>The task controller class.
$methodstringThe controller method handler.

Return:

self - Returns the task scheduler.

Example:

A fully qualified class name and followed the method name.

$this->service(ExampleController::class, 'handlerMethodName');

Requirements

  • The class must extend Luminova\Base\Cli\AbstractController or Luminova\Base\Cli\AbstractConsole.
  • The method must be public and concrete. Static methods are supported.
  • The class is instantiated without constructor arguments.
  • For an instance method named run on an AbstractConsole subclass, the worker supplies its CLI input array. Any other method is called without arguments.

The method's return value does not decide whether the task succeeded.It is written to the task output.A task is marked as failed only when the class is not a valid command,or the method does not exist or can't be called.

Tasks are stored by their Class::method string, so registering the same controller and method twice results in a single task.



Callbacks and pings

These methods allow you to react when a task completes or fails.

Callbacks receive the task information array. Ping requests are sent through the framework HTTP client service and include the task information as the request body.

onComplete

Callback to execute when the task completes.

protected final function onComplete(callable $onComplete): self

Parameters:

ParameterTypeDescription
$onComplete\ClosureThe callback function to execute on completion.
- Closure with one array parameter of task details.

Return:

self - Returns the task scheduler.


onFailure

Callback to execute when the task fails.

protected final function onFailure(callable $onError): self

Parameters:

ParameterTypeDescription
$onError\ClosureThe callback function to execute on failure.
- Closure with one array parameter of task details.

Return:

self - Returns the task scheduler.


pingOnComplete

URL to send a POST request to when the task completes.

The request payload will contain the executed task details.

protected final function pingOnComplete(string $url): self

Parameters:

ParameterTypeDescription
$urlstringThe URL to ping on completion.

Return:

self - Returns the task scheduler.


pingOnFailure

URL to send a POST request to when the task fails.

The request payload will contain the executed task details.

protected final function pingOnFailure(string $url): self

Parameters:

ParameterTypeDescription
$urlstringThe URL to ping on failure.

Return:

self - Returns the task scheduler.


Output Options

Define output location, error log destination including task description for easy debugging.

description

The description method sets a short description for the task. It is saved with the task and shown in the execution output header.

protected final function description(string $description): self

Parameters

ParameterTypeDescription
$descriptionstringThe task description message.

Return:

self - Returns the task scheduler.


log

The log method sets the log level used to record anything the task prints while it runs. Captured output is sent to the application logger at the given level. Nothing is logged when the task produces no output.

protected final function log(string $level): self

Parameters

ParameterTypeDescription
$levelstringThe log level (e.g, notice, error).

Return:

self - Returns the task scheduler.

Throws

Luminova\Exceptions\InvalidArgumentException if an unsupported log level is provided.

$this->service(ServiceTwoCommand::class, 'barMethod')
    ->minutes(10)
    ->log('info');

output

The output method sets a file where the execution messages for the task are written, such as the header, retry notices, and success or failure status.

protected final function output(string $filepath): self

Parameters

ParameterTypeDescription
$filepathstringThe task execution output path.

Return:

self - Returns the task scheduler.

Throws

Luminova\Exceptions\InvalidArgumentException if the file path is invalid.

A valid path contains only letters, numbers, underscores, dots, hyphens, and forward slashes. Spaces, backslashes, drive letters, double slashes, and the characters < > : " | ? * are rejected. The directory is created automatically when it does not exist.

$this->service(ServiceOneCommand::class, 'fooMethod')
    ->seconds(5)
    ->output(root('/writeable/log/', 'cron-one.log'));

Note:The file is overwritten on each run, so it only contains the latest execution output.


Intervals

Each service needs an interval. Every interval method accepts an integer, and values lower than 1 are raised to 1.

The interval is calculated using the application timezone, set by the app.timezone environment key (default: UTC).

$this->service(ReportCommand::class, 'daily')
    ->days(1);

expression

The expression method sets the interval from a standard five part cron expression instead of using one of the interval methods above.

protected final function expression(string $interval): self

Parameters

ParameterTypeDescription
$intervalstringA cron interval expression in the format minute hour day month weekday.

Return:

self - Returns the task scheduler.

Throws

Luminova\Exceptions\RuntimeException if the expression is empty, shorter than five characters, or does not have exactly five parts.

$this->service('\App\Controllers\Cli\CleanupCommand::run')
    ->expression('*/15 * * * *');

Common expressions map directly to an interval:

ExpressionInterval
* * * * * and */N * * * * (N = 1, 2, 3, 5, 10, 15, 30)Every N minutes
0 * * * * and 0 */N * * * (N = 1, 2, 3, 4, 6, 12)Every N hours
0 0 */N * * (N = 3, 5, 7, 10, 15, 30)Every N days
0 0 * * 0Every week
* * * * 0On Sunday
0 0 1 * *First day of the month
0 0 28-31 * *Last day of the month
0 0 1 */N * (N = 1, 2, 3, 4, 6, 12)Every N months
0 0 1 1 *January 1st each year

Other valid five part expressions are approximated as a fixed number of seconds, calculated when the lock file is created. For predictable results, prefer one of the expressions above or an interval method.

Note:

Intervals are measured from the last execution of the task, not aligned to the clock.For example, 0 * * * * runs once an hour after the previous run, not at minute zero.


seconds

Run every given number of seconds.

protected final function seconds(int $seconds = 5): self

Parameters:

ParameterTypeDescription
$secondsintInterval in seconds (default: 5).

Return:

self - Return cron schedular class instance.


minutes

Run every given number of minutes.

protected final function minutes(int $minutes = 1): self

Parameters:

ParameterTypeDescription
$minutesintInterval in minutes.

Return:

self - Return cron schedular class instance.


hours

Run every given number of hours.

protected final function hours(int $hours = 1): self

Parameters:

ParameterTypeDescription
$hoursintInterval in hours.

Return:

self - Return cron schedular class instance.


days

Run every given number of days.

protected final function days(int $days = 1): self

Parameters:

ParameterTypeDescription
$daysintInterval in days.

Return:

self - Return cron schedular class instance.


weeks

Run every given number of weeks.

protected final function weeks(int $weeks = 1): self

Parameters:

ParameterTypeDescription
$weeksintInterval in weeks.

Return:

self - Return cron schedular class instance.


months

Run every given number of months.

protected final function months(int $months = 1): self

Parameters:

ParameterTypeDescription
$monthsintInterval in months.

Return:

self - Return cron schedular class instance.


years

Run every given number of years.

protected final function years(int $years = 1): self

Parameters:

ParameterTypeDescription
$yearsintInterval in years.

Return:

self - Return cron schedular class instance.


Customizing the Lock File Location

Task state is stored in a JSON lock file. By default it is created at /writeable/cron/schedules.json, and the directory is created automatically.

To use a different directory or file name, set the $lockPath or $filename static property in onCreate() before defaults are applied.

// /app/Tasks/TaskScheduler.php
namespace App\Tasks;

use Luminova\Base\AbstractTaskScheduler;

final class TaskScheduler extends AbstractTaskScheduler
{
    public function onCreate(): void
    {
        self::$lockPath = '/path/to/cron/';
    }

    protected function schedule(): void
    {
        // ...
    }
}

The lock file keeps the state of each task, including its last execution time, completed runs, failures, and retries.


Running Scheduled Tasks

Tasks are created and executed with the cron command group in Novakit.

php novakit cron:create
php novakit cron:run
CommandOptionDescription
cron:create-f, --forceRebuild the lock file from the current schedule method.
cron:run-f, --forceRebuild the lock file, then run due tasks.
cron:run-s, --sleepDelay in seconds between tasks (default: 0.1).

Important behavior

  • The lock file is only built when it does not exist. After you add, remove, or change a service in schedule, run cron:create --force (or cron:run --force) so the changes take effect.
  • The first cron:run after the lock file is created executes every task.
  • A task that failed on its last run is retried on the next cron:run, regardless of its interval.

Full Example

Below is a complete example of the TaskScheduler class configuration:

// /app/Tasks/TaskScheduler.php
namespace App\Tasks;

use Luminova\Base\AbstractTaskScheduler;
use function Luminova\Funcs\root;

final class TaskScheduler extends AbstractTaskScheduler
{
    /**
     * Define and schedule tasks for cron execution.
     */
    protected function schedule(): void
    {
        $this->service(ServiceOneCommand::class, 'fooMethod')
            ->seconds(5)
            ->description('Sync foo records')
            ->output(root('/writeable/log/', 'cron-one.log'));

        $this->service(ServiceTwoCommand::class, 'barMethod')
            ->minutes(10)
            ->log('info');

        $this->service(CleanupCommand::class, 'run')
            ->expression('0 0 */7 * *');
    }
}

Additional Resources