PHP Luminova: Scheduling Background Tasks in Filesystem Storage
Define scheduled tasks, execution intervals, callbacks, and output for the filesystem scheduler.
The App\Tasks\TaskScheduler class is the configuration for defining and scheduling tasks executed by the cron task manager. It extends Luminova’s AbstractTaskScheduler and allows you to register services and set how often each one runs.
Tasks are defined by implementing the
schedulemethod, to register task's controller class and method
Class Definition
- Full namespace:
App\Tasks\TaskScheduler - This class extends Luminova\Base\AbstractTaskScheduler.
- This class is final.
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. Set app.timezone for the default timezone, or call timezone() for a particular task.
protected function onCreate(): voidExample
protected function onCreate(): void
{
self::$lockPath = 'path/to/cron/';
self::$filename = 'schedules.json';
}Note:Properties not explicitly configured in
onCreateretain 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(): voidResponsibilities
- 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 with a public method.
protected final function service(string $class, string $method): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$class | class-string<AbstractController>|class-string<AbstractConsole> | The task controller class. |
$method | string | The controller method handler. |
Return:
self - Return cron schedular instance.
Example:
A fully qualified class name and followed the method name.
$this->service(ExampleController::class, 'handlerMethodName');Requirements
- The class must extend
Luminova\Base\Cli\AbstractControllerorLuminova\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
runon anAbstractConsolesubclass, the worker passes the 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): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$onComplete | callable | The callback function to execute on completion. - Closure with one array parameter of task details. |
Return:
self - Return cron schedular instance.
onFailure
Callback to execute when the task fails.
protected final function onFailure(callable $onError): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$onError | callable | The callback function to execute on failure. - Closure with one array parameter of task details. |
Return:
self - Return cron schedular instance.
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): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$url | string | The URL to ping on completion. |
Return:
self - Return cron schedular instance.
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): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$url | string | The URL to ping on failure. |
Return:
self - Return cron schedular instance.
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): selfParameters
| Parameter | Type | Description |
|---|---|---|
$description | string | The task description message. |
Return:
self - Return cron schedular instance.
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): selfParameters
| Parameter | Type | Description |
|---|---|---|
$level | string | The log level (e.g, notice, error). |
Return:
self - Return cron schedular instance.
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): selfParameters
| Parameter | Type | Description |
|---|---|---|
$filepath | string | The task execution output path. |
Return:
self - Return cron schedular instance.
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): selfParameters
| Parameter | Type | Description |
|---|---|---|
$interval | string | A cron interval expression in the format minute hour day month weekday. |
Return:
self - Return cron schedular instance.
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:
| Expression | Interval |
|---|---|
* * * * * 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 * * 0 | Every week |
* * * * 0 | On 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): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$seconds | int | Interval in seconds (default: 5). |
Return:
self - Returns the scheduler.
minutes
Run every given number of minutes.
protected final function minutes(int $minutes = 1): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$minutes | int | Interval in minutes. |
Return:
self - Returns the scheduler.
hours
Run every given number of hours.
protected final function hours(int $hours = 1): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$hours | int | Interval in hours. |
Return:
self - Returns the scheduler.
days
Run every given number of days.
protected final function days(int $days = 1): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$days | int | Interval in days. |
Return:
self - Returns the scheduler.
weeks
Run every given number of weeks.
protected final function weeks(int $weeks = 1): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$weeks | int | Interval in weeks. |
Return:
self - Returns the scheduler.
months
Run every given number of months.
protected final function months(int $months = 1): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$months | int | Interval in months. |
Return:
self - Returns the scheduler.
years
Run every given number of years.
protected final function years(int $years = 1): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$years | int | Interval in years. |
Return:
self - Returns the scheduler.
interval
Schedule a repeat interval using a PHP date interval. For example, interval('PT', 10, 'S') schedules a run every ten seconds.
public function interval(string $format, int $value, string $designator): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$format | string | Period prefix. Use P for dates or PT for times. |
$value | int | Interval amount. |
$designator | string | Unit designator, such as D for days or S for seconds. |
Return:
self - The scheduler.
calendar
Schedule a task for a particular date and time. Create the lock file before the target time so that the first run can become due.
public function calendar(DateTimeInterface|string $datetime): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$datetime | DateTimeInterface|string | Target time. A string without a timezone uses the scheduler’s active timezone. |
Return:
self - The scheduler.
Throws:
- InvalidArgumentException when the date cannot be parsed.
timezone
Set the timezone for the current service. To parse a calendar date in this timezone, call timezone() before calendar().
public function timezone(DateTimeZone|string $timezone): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$timezone | DateTimeZone|string | Timezone object or valid identifier, such as Asia/Kuala_Lumpur. |
Return:
self - The scheduler.
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;
final class TaskScheduler extends \Luminova\Base\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| Command | Option | Description |
|---|---|---|
cron:create | -f, --force | Rebuild the lock file from the current schedule method. |
cron:run | -f, --force | Rebuild the lock file, then run due tasks. |
cron:run | -s, --sleep | Delay 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, runcron:create --force(orcron:run --force) so the changes take effect. - For recurring tasks, the initial timestamp is the time the lock file is created. The first run becomes due after the configured interval.
- 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 configuration:
// /app/Tasks/TaskScheduler.php
namespace App\Tasks;
use function Luminova\Funcs\root;
final class TaskScheduler extends \Luminova\Base\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 * *');
}
}