PHP Luminova: Schedule Background Tasks with a Filesystem Lock File
Register scheduled controller methods and run due tasks with Novakit using a JSON lock file.
The Filesystem Task Queue Abstract Class is a base for implementing a scheduler for recurring tasks. Extend AbstractTaskScheduler in App\Tasks\TaskScheduler and implement schedule() to register your task handlers and their intervals. Novakit’s cron commands load that schedule and run the handlers when they are due. The scheduler stores task state in a JSON lock file.
To define tasks, intervals, logging, and output, see Filesystem Task Queue. For database backed processing, see Database Background Tasks Execution.
Example
// /app/Tasks/TaskScheduler.php
namespace App\Tasks;
use App\Controllers\Cli\{ServiceOneCommand, ServiceTwoCommand};
use Luminova\Base\AbstractTaskScheduler;
use function Luminova\Funcs\root;
final class TaskScheduler extends AbstractTaskScheduler
{
/**
* Define and schedule tasks for execution.
*/
protected function schedule(): void
{
$path = root('/writeable/log/');
$this->service(ServiceOneCommand::class, 'fooMethod')
->seconds(5)
->log('info')
->output($path . 'cron-one.log');
$this->service(ServiceTwoCommand::class, 'barMethod')
->days(2)
->log('info')
->output($path . 'cron-two.log');
}
}Class Definition
- Full namespace:
Luminova\Base\AbstractTaskScheduler - This class is abstract.
The task scheduler API reference covers registration, interval and calendar settings, and access to registered tasks.
Scheduler Hooks
onCreate
Override this hook to customize the lock directory or filename. The constructor calls it before applying the defaults. Set self::$lockPath to the directory and self::$filename to the lock filename.
protected function onCreate(): voidschedule
Implement this hook to register controller methods and configure their intervals.
abstract protected function schedule(): voidNovakit Commands
php novakit cron:create
php novakit cron:run| Command | Option | Description |
|---|---|---|
cron:create | -f, --force | Rebuild the lock file from the current schedule method. A success or failure message is printed only when this option is used. |
cron:run | -f, --force | Rebuild the lock file, then run due tasks. |
cron:run | -s, --sleep | Delay in seconds between tasks (default: 0.1). |
Both commands also accept the shared Novakit options --no-header, --no-color, --no-ansi, and -h, --help.
cron:create builds the lock file only when it does not exist, unless --force is used. cron:run creates the lock file first when it is missing, and exits with an error status if it cannot be created.
How Tasks Run
Each cron:run checks every task in the lock file, in order, and runs the ones that are due.
- A task whose last run failed is due again on the next
cron:run. - Tasks run one after another in the same process. A slow task delays the ones after it.
- A task can only run when
cron:runis invoked, so the crontab frequency is the smallest effective interval.
Due check
The due check depends on the interval stored for the task.
Interval-based schedules (
secondstoyears): A task is due once the current time reaches or passes its last execution time plus the configured interval. The interval is calculated in the scheduler timezone. When the lock file is created, the last execution time is initialized to that moment, so a new task waits for one full interval before its first run.Calendar-based schedules (ISO 8601 date/time strings): A task is due when the current time reaches or passes its target date and time, provided it has not already run at or after that target. The comparison uses the full date and time, not just the date. Create the lock file before the target time so its initial execution timestamp is earlier than the target. Once the target passes, a pending task can run on the next invocation.
Success and failure
A task succeeds when its method is called. The returned value is written to the task output and does not affect the result. A task fails when the class is not a routable CLI controller or Novakit console subclass, or when the method does not exist, is not public, or is abstract. Static methods are supported. Each failure increments the failures count, and each retry that returns a result increments retries. There is no retry limit.
If the task method throws an exception, the message, file, line, and exception class are sent to the log level set with log, or discarded when none is set. The exception details go to the logger. The output file can still contain text emitted before the exception. The run is not counted as completed or failed, the last execution date is not updated, and no callbacks or pings are triggered.
Callbacks and pings
After a task method is called, the worker runs the onComplete or onFailure callback and sends the matching ping request, if they were set. They are read from the current schedule method by task id, so run cron:create --force after you add, remove, or reorder services.
Lock File
By default the lock file is /writeable/cron/schedules.json. To change its location, see Customizing the Scheduler.
Each task entry records its description, controller, last execution time, whether the last run completed, and the completed, failures, and retries counts, along with its log, output, ping, and interval settings. For callbacks, only a flag is stored, because a callback cannot be saved in the file.
- Changes in
scheduleare not picked up while a lock file exists. After you add, remove, or change a service, runcron:create --force. - Services removed from
schedulestay in the lock file, and keep running while their class and method exist, until the file is rebuilt with--force.
Crontab Commands
To run the scheduler, add one of the following commands to your server's crontab. Use the same PHP binary your application runs on.
If you are using cPanel, you can use its PHP binary located at /usr/local/cpanel/3rdparty/bin/php.
Replace
/path/to/project/with the absolute path to your project directory and use the correct path to your PHP executable.
Using the Default PHP Binary
* * * * * cd /path/to/project/ && php novakit cron:run >> /dev/null 2>&1Using cPanel's PHP Binary
* * * * * cd /path/to/project/ && /usr/local/cpanel/3rdparty/bin/php novakit cron:run >> /dev/null 2>&1Logging Output to a File
To capture the output of cron:run for debugging, redirect standard output and errors to a log file.
* * * * * cd /path/to/project/ && php novakit cron:run >> /path/to/project/writeable/log/debug.log 2>&1Command Explanation
* * * * *runs the command every minute.cd /path/to/project/changes to the project directory.php novakit cron:runexecutes the scheduler.>> /dev/null 2>&1discards standard output and errors.>> /path/to/project/writeable/log/debug.log 2>&1appends standard output and errors to the log file.
Force Job Recreation
The --force flag rebuilds the lock file from schedule before running tasks. Use it once after you add or change services, or run php novakit cron:create --force instead.
php novakit cron:run --forceCaution
Rebuilding the lock file resets every task's last execution time and its completed, failures, and retries counts. Do not add --force to your crontab, because the task state would be reset on every invocation.
Note:
- The crontab interval controls how often Luminova checks the lock file for due tasks.
- Run the crontab every minute for regular checks. A longer crontab interval delays tasks accordingly.
Full Configuration Example
The following example schedules a daily task with completion and failure callbacks, logging, output, and a description.
For details about each execution interval method, see Core Task Execution Intervals.
$this->service(DailyCommand::class, 'dailyBackup')
->days()
->pingOnComplete('https://example.com/ping/daily/success')
->pingOnFailure('https://example.com/ping/daily/failure')
->onComplete(function(array $task): void {
// Code to execute after successful task completion
})
->onFailure(function(array $task): void {
// Code to execute after task failure
})
->output('path/to/log/daily/output/file.log')
->log('info')
->description('This is my daily command description');Note:
Other interval methods include
seconds(),minutes(),hours(),weeks(),months(),years(),interval(),calendar(), andexpression().Do not combine multiple execution interval methods in a single service configuration.Choose the interval method that matches the intended schedule.Other configuration methods can be chained as needed.