PHP Luminova: Database Queue for Background Tasks
Stage, enqueue, and process background tasks with a database-backed queue.
The Database Task Queue Abstract Class is a base for implementing queues backed by a database. Implement tasks() in your subclass to supply task definitions or return null when there is nothing to enqueue. The base class provides operations for enqueuing tasks, tracking their status, and processing them with a worker. You can manage the queue through Novakit or from PHP.
Background tasks are jobs that take time to complete or are not urgent, such as sending a welcome email, generating a sitemap, or sending push notifications. The user doesn't need to wait for the result, so the task is placed in a queue and processed by a worker.
Queue operations include retrying failed tasks and pausing or resuming processing.
If you're building something fixed and periodic that doesn't need database scheduling,
Luminova\Base\AbstractTaskSchedulerworks, but it's rigid.If you need dynamic, programmatic task scheduling, runtime safety, and monitoring,Luminova\Base\AbstractTaskQueueis the practical and extensible choice.
Database support:
Table creation supports MySQL, SQLite, SQL Server, Oracle and MS Access, but the queries usedto select and insert tasks are currently written in MySQL syntax (
NOW(),TIMESTAMPDIFF()andON DUPLICATE KEY UPDATE). Use MySQL or MariaDB for the queue.
Task Handler Formats
A task handler is the method or function that the queue will run. You can define the handler using any of the formats below:
A plain function nameExample:
sendEmailA static methodExample:
App\Utils\Worker::processA class and method using instance styleExample:
App\Utils\Worker@cleanA
[class, method]array, which is converted to the static format (Class::method). The method must exist, otherwise aRuntimeExceptionis thrown.Example:[App\Utils\Worker::class, 'process']An invokable class that implements
Luminova\Interface\InvokableInterfaceorLuminova\Interface\QueueableInterfaceExample:App\Utils\WorkerAn anonymous class or closure serialized with
Luminova\Utility\SerializerorOpis\Closure\SerializerAnonymous classes must implementQueueableInterfaceand define__invoke().
Note:
The
$isClosureSupportedproperty enables theisClosure()check for serialized handlers.The defaultApp\Tasks\TaskQueueclass sets it totrue.
CLI Integration
The task queue works with the novakit command line tool, which allows you to add, list, delete, or run tasks from the terminal.
To learn how to use the CLI tool, see the Task Execution & Novakit Commands documentation.
Usages
Default Application Task Queue:
When Luminova is installed, a default task queue class is created at app/Tasks/TaskQueue.php if it doesn't already exist. To start using background tasks, set up crontab in production and run the following command once:
php novakit task:initAfter initialization and crontab setup, you can queue tasks from the CLI or directly in your PHP code.
Example Task Queue Class:
// app/Tasks/ExampleTask.php
namespace App\Tasks;
use Luminova\Base\AbstractTaskQueue;
class ExampleTask extends AbstractTaskQueue
{
protected function onCreate(): void
{
// Optional: Code to run when the queue is created
}
public function tasks(): ?array
{
// Return your task definitions here if needed
return null;
}
}Adding a Task:
You can queue any valid handler, such as a named function:
function mySendMailFunction(string $to): bool
{
// send email...
return true;
}
$queue = new ExampleTask();
$queue->enqueue('mySendMailFunction', ['[email protected]']);Using the Singleton Instance:
use App\Tasks\ExampleTask;
$queue = ExampleTask::create();
$queue->enqueue('mySendMailFunction', ['[email protected]']);
$tasks = $queue->list(ExampleTask::ALL);Note:
Task arguments are stored as a positional list.Array keys are dropped, so use ordered arguments rather than named ones.Objects are not restored when the arguments are read back, so pass scalars and arrays only.
Anonymous Classes and Closures
You can enqueue either an anonymous class or a closure. Anonymous classes must implement QueueableInterface.
Anonymous Class Example:
use App\Tasks\TaskQueue;
use Luminova\Utility\Serializer;
$class = Serializer::serialize(new class() implements Luminova\Interface\QueueableInterface {
public function __invoke(mixed ...$arguments): mixed
{
return $this->greet(...$arguments);
}
public function deleteOnCompletion(): bool
{
return false;
}
private function greet(string $message): string
{
return $message;
}
});
TaskQueue::create()->enqueue($class, ['Hello from anonymous class!']);Closure Example:
use App\Tasks\ExampleTask;
use Luminova\Utility\Serializer;
$closure = Serializer::serialize(function (int $loop): int {
$i = 0;
do {
$i++;
} while ($i < $loop);
return $i;
});
ExampleTask::create()->enqueue($closure, [10]);Accessing Command Input in Handlers
When a task runs through php novakit task:run, a handler class that implements Luminova\Interface\TaskWorkerInterface receives the CLI input through setCommandInput() before it is called.
// app/Tasks/Jobs/Job.php
namespace App\Tasks\Jobs;
use Luminova\Command\Input;
use Luminova\Interface\TaskWorkerInterface;
class Job implements TaskWorkerInterface
{
protected ?Input $input = null;
public function setCommandInput(Input $input): self
{
$this->input = $input;
return $this;
}
public function run(array $options = []): mixed
{
if ($this->input === null) {
return 'Invalid command input';
}
// Use $this->input to read the worker command options
return null;
}
}Queue it using the instance format:
php novakit task:queue -t=App\\Tasks\\Jobs\\Job@runEnsuring Task Reliability
The queue decides the outcome of a task by whether the handler throws. The return value is stored as the task response but does not affect the status.
Implementation Guidelines:
- Success: Let the handler finish without throwing an exception. A task that finishes is marked
completed, whatever it returns. - Failure: Throw an exception for any failure. The task is marked
failedand the exception message is saved as its output. - Retries: A failed task runs again only when it was queued with
retriesgreater than zero, and only until its attempts reach that limit. With the default of0, it staysfaileduntil you callretry().
Example
function sendWelcomeEmail(string $to): bool
{
$mailer = Luminova\Components\Email\Mailer::to($to)
->subject('Welcome!')
->body('Thanks for joining...');
if ($mailer->send()) {
return true;
}
// Throwing marks the task as failed
throw new Exception('Email delivery failed to: ' . $to);
}// Retry up to 3 times if the task fails
ExampleTask::create()->enqueue(
'sendWelcomeEmail',
['[email protected]'],
retries: 3
);Why this matters:
- Failures are recorded with their output instead of passing silently
- A retry limit prevents non-critical tasks from looping forever
- It helps with temporary issues, such as a mail server being unavailable
How Tasks Run
The worker processes executable tasks ordered by priority (0 runs first), then scheduled time, then ID. A task is executable when it is not scheduled for the future and meets one of these conditions:
- Its status is
pending. - It is
failed, hasretriesgreater than zero, and its attempts are below that limit. - It is a forever task whose status is
pending,failedorcompleted, and its last update is at leastforeverminutes old.
Before running a task, the worker verifies its stored signature (an XXH3 hash of the handler and arguments). Tasks with a signature mismatch are skipped.
When a task completes, it is deleted instead of updated if any of these apply, unless it is a forever task:
- It was queued with
$deleteOnComplete = true. - The queue class sets
$deleteOnCompletiontotrue. - The handler implements
QueueableInterfaceanddeleteOnCompletion()returnstrue.
If a handler cannot be resolved, the task is not updated. In CLI mode the error is logged and the worker moves on. Outside the CLI, a RuntimeException is thrown.
Class Definition
- Full namespace:
Luminova\Base\AbstractTaskQueue - This class is abstract.
Constants
Task Status & Filter Constants
These constants define the possible statuses for queued tasks and the filters used when querying the queue.
Task Execution Statuses
| Constant | Type | Description |
|---|---|---|
PENDING | string | Task is waiting to be picked up by the worker. |
PAUSED | string | Task is paused and will not run until resumed. |
RUNNING | string | Task is currently being processed. |
FAILED | string | Task execution failed. Usually caused by an exception. |
COMPLETED | string | Task finished successfully and may be deleted if configured. |
Task Result Filters
| Constant | Visibility | Type | Description |
|---|---|---|---|
ALL | public | string | Matches tasks of all statuses. |
FOREVER | public | string | Matches tasks scheduled to run repeatedly, which are never auto-removed. |
EXCEPTION | protected | string | Identifies tasks whose handler could not be resolved or called. |
PAUSEABLE | protected | string | Matches tasks that can be paused (pending or failed). |
EXECUTABLE | protected | string | Matches tasks that are ready for execution. |
Properties
onError
Task error callback.
This callback runs when a task ends in any status other than completed. The exception it receives wraps the task output. When no callback is set, the failure is written to the notice log.
protected ?Closure $onError = null;Callback Signature:
$this->onError = static function(int $id, string $status, Throwable $e){
// Handle error
};table
Task database table name used for persistence.
protected string $table = '`task_queue`';group
A unique identifier for this task queue group.
The value identifies and manages tasks when multiple queue classes share the same database table. Every query is limited to the current group, so a worker only runs the tasks of its own group.
protected ?string $group = null;Note:The group name should not exceed 150 characters. When it is
null, the short class name is used.
deleteOnCompletion
Automatically delete tasks after successful completion.
When true, completed tasks and their output are removed immediately after execution and no longer appear in task listings. Forever tasks are never deleted.
protected bool $deleteOnCompletion = false;isClosureSupported
Flag to enable or disable support for serialized closure handlers.
When true, isClosure() recognizes serialized closures created with Luminova\Utility\Serializer or Opis\Closure\Serializer. This allows you to store closures and anonymous classes as strings and restore them when the task runs.
protected bool $isClosureSupported = false;stopSignalFile
File path used to signal background workers to stop.
When this file exists, the active worker shuts down gracefully. The worker only checks for the file when this property is set.
protected ?string $stopSignalFile = null;Note:To send a signal for the worker to run again, run
php novakit task:sig --resume-workeror delete the file manually.
taskEventTailing
Enable event logging for task execution monitoring.
When true, task start and finish events are written to a log file while running tasks from the CLI. Use php novakit task:tail to watch the log. The log file is cleared each time a worker starts.
public bool $taskEventTailing = false;ignores
List of task handlers that should be skipped when queuing.
/**
* @var string[]
*/
protected array $ignores = [];input
Terminal command input, available when the queue is created by Novakit commands.
protected ?Input $input = null;running
Worker is currently running.
When SIGTERM or SIGINT is received, the worker is stopped.
protected bool $running = true;Methods
__construct
Initialize a new task queue instance.
By default, the task system uses App\Tasks\TaskQueue as the queue class. You can extend it to create and manage custom task queues per domain or module.
public function __construct()Note:
The constructor creates the internal database connection and then calls
onCreate().If you override__construct(), you must callparent::__construct()or useonCreate()for custom initialization logic.
CLI Usage:
php novakit task:queue # Loads and enqueues tasks from tasks() and stage()
php novakit task:queue -t=App\\Utils\\Worker@clean -a='["temp"]' -s='+10 minutes'Programmatic Usage:
$queue = new \App\Tasks\ExampleTask();
$queue->enqueue('App\Utils\Worker@clean', ['temp'], '+10 minutes');
// Or the shared instance
\App\Tasks\ExampleTask::create()
->enqueue('App\Utils\Worker@clean', ['temp'], '+10 minutes');create
Get the singleton instance of the called class.
public static function create(): staticReturn:
static<Luminova\Base\AbstractTaskQueue> - Returns the shared instance of the class, created on first call.
__callStatic
Route a static call to the singleton instance.
This is only used for static calls to methods that cannot be called directly. For public methods such as enqueue(), use create().
public static function __callStatic(string $method, array $arguments): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$method | string | The method name. |
$arguments | array<array-key, mixed> | Arguments to pass to the method. |
Return:
mixed - Returns the method response.
Throws:
\Luminova\Exceptions\BadMethodCallException- If the method does not exist.
onCreate
Hook method for custom initialization logic during construction.
This method is called after the database connection is initialized. Override it to perform setup without overriding __construct().
protected function onCreate(): voidExample:
// /app/Tasks/ExampleTask.php
namespace App\Tasks;
use Luminova\Base\AbstractTaskQueue;
class ExampleTask extends AbstractTaskQueue
{
protected function onCreate(): void
{
$this->ignores = ['App\Tasks\DebugTask@run'];
}
}tasks
Define tasks to preload into the queue when php novakit task:queue runs without a --task option.
Return an array of task definitions, or null to skip. The tasks are queued with an initial status of pending through batchEnqueue().
abstract protected function tasks(): ?arrayEach task is an associative array with the following keys:
handler(string, required): A valid handler, such asClass@method,Class::method, orfunction_name.arguments(array, optional): Arguments to pass to the handler.scheduled_at(DateTimeInterface|string|int|null, optional): Delay the task (e.g.DateTime, Unix timestamp, or relative time).priority(int): Task priority (0 = highest, 100 = lowest). Always set it explicitly.forever(int|null, optional): Interval in minutes between repeats (minimum 5, e.g.1440for once a day).retries(int, optional): Number of times to retry a failed task.auto_delete(bool, optional): Delete the task once it completes.
Return:
array<int,array<string,mixed>>|null - Returns task definitions to enqueue, or null to skip.
// /app/Tasks/ExampleTask.php
namespace App\Tasks;
use Luminova\Base\AbstractTaskQueue;
class ExampleTask extends AbstractTaskQueue
{
public function tasks(): ?array
{
return [
[
'handler' => 'App\Services\Mailer@sendWelcomeEmail',
'arguments' => ['[email protected]'],
'priority' => 0
],
[
'handler' => 'App\Utils\Cleanup::purgeTempFiles',
'scheduled_at' => '+5 minutes',
'priority' => 5,
'forever' => 1440
],
];
}
}stage
Stage a task to be queued later by php novakit task:queue.
This method does not write to the database. It keeps the task in an internal list, which getStagedTasks() returns together with the tasks from tasks(). Use it inside subclasses, for example in onCreate() or tasks().
protected final function stage(
array|string $handler,
array $arguments = [],
DateTimeInterface|string|int|null $schedule = null,
int $priority = 0,
?int $forever = null,
int $retries = 0,
bool $deleteOnComplete = false
): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$handler | array<array-key, mixed>|string | The task handler reference (e.g. function name, Class@method, Class::method, or an invokable class). |
$arguments | array<array-key, mixed> | Optional arguments to pass to the task on execution. |
$schedule | DateTimeInterface|string|int|null | Optional delay for task execution (default: null). |
$priority | int | Optional priority (0 = highest, 100 = lowest) (default: 0). |
$forever | int|null | Optional interval in minutes for repeated execution (e.g. 1440 = once per day). |
$retries | int | Number of times to retry the task if it fails (default: 0, no retry). |
$deleteOnComplete | bool | If true, delete the task once completed (default: false). |
Return:
self - Returns the current instance, so calls can be chained.
Note:Staged tasks are queued through
batchEnqueue(), which reads the delay from thescheduled_atkey. The$schedulevalue stored bystage()is not applied at that point.
Example:
Queue a repeating task:
protected function onCreate(): void
{
$this->stage(
handler: 'App\Tasks\Jobs\SystemTasks::run',
arguments: ['API_STATUS'],
forever: 1440, // Run once every 24 hours
priority: 3
)->stage(
handler: 'App\Tasks\Jobs\SystemTasks::run',
arguments: ['CLEAR_CACHES'],
forever: 1440,
priority: 5
);
}getStagedTasks
Get all staged tasks, combining those returned by tasks() and those added with stage().
Novakit uses this method to collect tasks before task:queue pushes them to the database.
public function getStagedTasks(): arrayReturn:
array<int,array> - Returns a merged array of all staged tasks.
enqueue
Queue a new task for background execution.
public function enqueue(
array|string $handler,
array $arguments = [],
DateTimeInterface|string|int|null $schedule = null,
int $priority = 0,
?int $forever = null,
int $retries = 0,
bool $deleteOnComplete = false
): intParameters:
| Parameter | Type | Description |
|---|---|---|
$handler | array<array-key, mixed>|string | The task handler reference (e.g. function name, Class@method, Class::method, or a [class, method] array).Or a class that implements Luminova\Interface\QueueableInterface or Luminova\Interface\InvokableInterface. |
$arguments | array<array-key, mixed> | Optional arguments to pass to the handler on execution. They are stored as an ordered list. |
$schedule | DateTimeInterface|string|int|null | Optional delay for task execution (default: null).Accepts DateTime, Unix timestamp, or relative time.If null or not parseable, the task is due immediately. |
$priority | int | Optional priority (0 = highest, 100 = lowest). Values outside the range are clamped. Default is 0. |
$forever | int|null | Interval in minutes between repeated executions for a forever task (default: null).Must be 5 or more (e.g. 1440 = once per day). |
$retries | int | Number of times to retry the task if it fails (default: 0, no retry). |
$deleteOnComplete | bool | If true, delete the task once it completes (default: false). Ignored for forever tasks. |
Return:
int - Returns the inserted task ID on success, or 0 if the insert failed or the handler is empty or listed in $ignores.
Throws:
- Luminova\Exceptions\DatabaseException - If a database error occurs.
- Luminova\Exceptions\InvalidArgumentException - If an invalid forever interval is provided.
- Luminova\Exceptions\RuntimeException - If a handler array is not a valid
[class, method]pair or the method does not exist.
Note: Each task gets a signature from its handler and arguments. Queuing the same handler and arguments again resets the matching task to
pendingand clears its output and attempts, instead of adding a new row.
Example:
$queue->enqueue(
handler: App\Utils\Mailer::class . '@send',
arguments: ['[email protected]', 'welcome-template'],
schedule: '+5 minutes',
priority: 1
);Forever task example:
$queue->enqueue(
handler: 'App\Utils\Cleaner::purgeTemp',
schedule: '+5 minutes',
priority: 10,
forever: 720 // Run forever, every 12 hours
);batchEnqueue
Queue multiple tasks in a single transaction.
Each item is an associative array or a Luminova\Models\Task instance. Items are read with these keys:
handler(string): The handler, e.g.Class@methodorfunction_name.arguments(array): Parameters to pass to the handler.scheduled_at(DateTimeInterface|string|int|null): Delay task execution.priority(int): Priority of execution (0 = highest). Set it explicitly for every item.forever(int|null): Interval in minutes between repeats.retries(int): Number of times to retry a failed task.auto_delete(bool): Delete the task once completed.
Tasks whose handlers are listed in $ignores are skipped. If the transaction is supported, each task is saved under its own savepoint and the batch is committed only when at least one task was inserted.
public function batchEnqueue(array $tasks): intParameters:
| Parameter | Type | Description |
|---|---|---|
$tasks | array<int, array<string, mixed>|Task> | Array of task definitions. |
Return:
int - Returns the number of tasks inserted.
Throws:
- Luminova\Exceptions\DatabaseException - If a database connection or execution error occurs.
- Luminova\Exceptions\InvalidArgumentException - If an invalid forever interval is provided.
Example:
$queue->batchEnqueue([
['handler' => 'App\Utils\Mailer@send', 'arguments' => ['[email protected]'], 'priority' => 0],
['handler' => 'App\Utils\Webhook::send', 'priority' => 10, 'scheduled_at' => '+5 minutes'],
['handler' => 'App\Utils\Cleaner::purgeTemp', 'priority' => 0, 'forever' => 1440]
]);run
Start the task worker loop and continuously process executable tasks.
The loop runs until one of the following happens:
- A stop signal (
SIGTERM,SIGINT) is received. Signal handling needspcntland CLI mode. - The stop signal file is detected (only when
$stopSignalFileis set). - The maximum number of idle cycles is reached (no executable tasks).
Tasks are fetched ordered by priority, then scheduled time, then ID. Between batches the worker sleeps for an adaptive delay, clamped between 50,000 and 1,000,000 microseconds when a batch has more than one task. Status messages are printed with echo.
public final function run(
float|int $sleep = 0.001,
?int $limit = null,
int $maxIdle = 10,
?int $id = null
): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$sleep | float|int | Base delay between task cycles. Novakit passes an integer in microseconds (default 100000). |
$limit | int|null | Maximum number of tasks to fetch per cycle. null for no limit. |
$maxIdle | int | Maximum consecutive idle cycles before the worker shuts down (default: 10). |
$id | int|null | Optional task ID to run only that task. |
Throws:
- Luminova\Exceptions\RuntimeException - If an unrecoverable error occurs, or a task handler cannot be resolved outside the CLI.
- Luminova\Exceptions\DatabaseException - If the database is not connected or a query fails.
Example:
$queue = new \App\Tasks\ExampleTask();
$queue->run(100000, 10, 3);
// Results of each executed task, keyed by task ID
$results = $queue->getResult();shutdown
Gracefully stop task execution.
This method sets the $running flag to false, resets tasks of this group that are still running back to pending (clearing their output), closes the database connection and releases the lock. If a signal is provided, it prints the signal number and process ID.
public function shutdown(?int $signal = null): voidParameters:
| Parameter | Type | Description |
|---|---|---|
$signal | int|null | Optional POSIX signal number (e.g. SIGTERM, SIGINT). |
getResult
Get the results of executed tasks.
When tasks run outside the CLI, this method returns the collected result of each task, keyed by task ID, with status, id, output and response.
public function getResult(): arrayReturn:
array<array-key, mixed> - Returns an associative array of task results.
get
Retrieve a task by ID within the current group.
public function get(int $id): Task|array|nullParameters:
| Parameter | Type | Description |
|---|---|---|
$id | int | The task's unique ID. |
Return:
Luminova\Models\Task|array<string,mixed>|null - Returns the task, or null if not found. Novakit commands receive an associative array.
Throws:
- Luminova\Exceptions\DatabaseException - If the database connection fails or a query error occurs.
list
Get a list of tasks, optionally filtered by status, limit and offset.
Tasks are ordered by priority, scheduled time, then ID.
public function list(
string $status = self::ALL,
?int $limit = null,
int $offset = 0,
bool $withTotal = false
): ?arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$status | string | Task status to filter by. Use all for every status (default: all). |
$limit | int|null | Maximum number of tasks to retrieve. null for no limit (default: null). |
$offset | int | The offset to start from (default: 0). |
$withTotal | bool | Whether to include the total task count in the result (default: false). |
Return:
array<array-key, mixed>|null - Returns an array of tasks, or null if none were found.
- When
$withTotalistrue, the structure is['total' => int, 'count' => int, 'tasks' => array].
Throws:
- Luminova\Exceptions\RuntimeException - If the status is invalid.
- Luminova\Exceptions\DatabaseException - If the database connection fails or a query error occurs.
find
Find tasks by ID and/or status. list() calls this method without an ID.
public function find(
?int $id = null,
string $status = self::ALL,
?int $limit = null,
int $offset = 0,
bool $withTotal = false
): ?arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$id | int|null | Task ID to find. If null, multiple tasks are returned. |
$status | string | Status to filter by. Accepts all, forever, executable or a task status (default: all). |
$limit | int|null | Maximum number of tasks to retrieve (default: null). |
$offset | int | The offset to start from (default: 0). |
$withTotal | bool | Whether to include the total task count in the result (default: false). |
Return:
array<array-key, mixed>|null - Returns the matching tasks, or null if none were found.
Throws:
- Luminova\Exceptions\RuntimeException - If the status is invalid.
- Luminova\Exceptions\DatabaseException - If the database connection fails or a query error occurs.
count
Count the tasks matching a given status.
public function count(string $status = self::ALL): intParameters:
| Parameter | Type | Description |
|---|---|---|
$status | string | Task status to count (e.g. pending, failed, all).Also accepts forever and executable. |
Return:
int - Returns the number of matching tasks.
Throws:
- Luminova\Exceptions\RuntimeException - If the given status is invalid.
- Luminova\Exceptions\DatabaseException - If the database connection fails or a query error occurs.
status
Set the status of a task.
The new status must be one of pending, paused, running, failed or completed. Setting completed or failed adds one to the task's attempts, setting pending resets attempts to 0, and the stored output is cleared.
public function status(int $id, string $newStatus): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$id | int | The task ID. |
$newStatus | string | The new status. |
Return:
bool - Returns true if the task was updated.
Throws:
- Luminova\Exceptions\RuntimeException - If the status name is invalid.
- Luminova\Exceptions\DatabaseException - If the database is not connected or an error occurs.
retry
Reset a failed task back to pending. Only tasks currently failed are changed.
public function retry(int $id): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$id | int | The task ID to retry. |
Return:
bool - Returns true if the task was updated.
Throws:
- Luminova\Exceptions\DatabaseException - If the database is not connected or an error occurs.
pause
Pause a task by setting its status to paused, only if it is currently pending or failed.
public function pause(int $id): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$id | int | The task ID to pause. |
Return:
bool - Returns true if the task was paused, otherwise false.
Throws:
- Luminova\Exceptions\DatabaseException - If the database is not connected or an error occurs.
resume
Resume a paused task by setting its status to pending.
public function resume(int $id): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$id | int | The task ID to resume. |
Return:
bool - Returns true if the task was resumed, otherwise false.
Throws:
- Luminova\Exceptions\DatabaseException - If the database is not connected or an error occurs.
delete
Delete a task by ID within the current group.
public function delete(int $id): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$id | int | The task ID to delete. |
Return:
bool - Returns true if the task was deleted.
Throws:
- Luminova\Exceptions\DatabaseException - If the database is not connected or an error occurs.
purge
Delete all tasks of the current group with a given status.
public function purge(string $status = self::ALL): intParameters:
| Parameter | Type | Description |
|---|---|---|
$status | string | Status to match. Use all to delete everything, or forever to delete forever tasks. |
Return:
int - Returns the number of tasks deleted.
Throws:
- Luminova\Exceptions\RuntimeException - If the status name is invalid.
- Luminova\Exceptions\DatabaseException - If the database is not connected or an error occurs.
export
Export the tasks with the given status to a file.
The file is a PHP file that returns an array of task definitions, each with priority, forever, auto_delete, retries, handler, arguments, schedule and status.
If no path is provided, the file is written to writeable/exports/ using the class name with namespace separators replaced by underscores, for example App_Tasks_TaskQueue.txt.
public function export(string $status = self::ALL, ?string &$path = null, ?string &$metadata = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$status | string | Task status to filter by (default: all). |
$path | string|null | Optional path to write the exported file. Updated with the final path. |
$metadata | string|null | Optional output variable that receives export details (handler class, total exported, date). |
Return:
bool - Returns true if the export succeeded, false if there were no tasks or the file could not be written.
Throws:
- Luminova\Exceptions\FileException - If the directory cannot be created or is not writable.
init
Initialize the task queue system.
Creates the queue table if it doesn't exist. The table stores task metadata including priority, status, handler, attempts, signature, output and timestamps. If the table already exists, nothing changes. The database connection is closed afterward.
Supported drivers are mysql, sqlite, sqlsrv (or sql-server), oracle and ms-access.
public function init(): boolReturn:
bool - Returns true if the table was created or already exists.
Throws:
- Luminova\Exceptions\DatabaseException - If the connection is denied or the database driver is not supported.
isInitialized
Check if the task database table exists.
public function isInitialized(): boolReturn:
bool - Returns true if the table exists.
Throws:
- Luminova\Exceptions\DatabaseException - If the database is not connected.
deinit
Destroy the task queue system.
Drops the task table. When the table was dropped, the worker is stopped, the lock is released and the stop signal file is removed.
public function deinit(): boolReturn:
bool - Returns true if the table was dropped.
Throws:
- Luminova\Exceptions\DatabaseException - If the database is not connected or an error occurs during the drop.
close
Close the active database connection, if connected.
public function close(): boolReturn:
bool - Returns true if the connection was closed, false otherwise.
isLocked
Check if the task worker is currently locked.
public function isLocked(): boolReturn:
bool - Returns true if this instance holds the lock or another process holds the lock file.
lock
Acquire a non blocking file lock (flock) to prevent multiple workers of the same class from running together.
The lock file is writeable/locks/queues/task_{Class_Name}.lock, where namespace separators are replaced with underscores.
public function lock(?int $permission = 0770): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$permission | int|null | Directory permission mode. Currently not used. |
Return:
bool - Returns false only when the lock path cannot be resolved. A held lock is not reported by the return value, so call isLocked() first.
unlock
Release the lock acquired by lock().
If this instance holds the lock, it is released and the file handle is closed. Otherwise the lock file is deleted if it exists.
public function unlock(): boolReturn:
bool - Returns true if the lock was released or the lock file was deleted.
isClosure
Check if a task handler is a serialized closure. Returns false when $isClosureSupported is disabled.
public function isClosure(string $handler): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$handler | string | The handler string to check. |
Return:
bool - Returns true if the handler is a serialized closure.
getClosure
Get the class that serialized a closure handler.
public function getClosure(string $handler): ?stringParameters:
| Parameter | Type | Description |
|---|---|---|
$handler | string | The handler string to resolve. |
Return:
string|null - Returns Luminova\Utility\Serializer or Opis\Closure\Serializer, or null if the handler is not a serialized closure.
withClosure
Resolve a handler and return its closure provider and status.
public static function withClosure(string $handler): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$handler | string | The handler string to resolve. |
Return:
array{0:?string,1:bool} - Returns the provider class name and true for a closure, otherwise [null, false].
getGroup
Get the task group name.
If $group is set, it is returned. Otherwise the short class name (without the namespace) is used.
public function getGroup(): stringReturn:
string - Returns the group name used for this queue.
getPathInfo
Get the resolved directory and full file path for a worker context.
Supported contexts:
event: The task event log file,writeable/logs/queues/event_{Class_Name}_task.log. Requires$taskEventTailingto betrue.signal: The stop and resume signal file. Requires$stopSignalFileto be set.flock: The lock file that prevents duplicate workers.
public function getPathInfo(string $context): ?arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$context | string | One of event, signal or flock. |
Return:
array<array-key, mixed>|null - Returns [directory, file path], or null if the context is invalid or its configuration is missing.
Example:
[$path, $file] = $this->getPathInfo('event') ?? [null, null];
[$path, $file] = $this->getPathInfo('signal') ?? [null, null];
[$path, $file] = $this->getPathInfo('flock') ?? [null, null];setCommandInput
Set the command input for the queue, making CLI arguments and options available inside the queue and in handlers that implement TaskWorkerInterface. Novakit calls this for you.
public function setCommandInput(Input $input): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$input | Input | The command input instance. |
Return:
self - Returns the current instance.
update
Update a task's status and output, with an optional status filter.
protected final function update(
int $id,
string $status,
?string $filter = null,
?string $outputs = null
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$id | int | Task ID. |
$status | string | New status to set. |
$filter | string|null | Only update when the current status matches this. Special values: pauseable allows pending and failed, forever allows forever tasks. |
$outputs | string|null | Optional JSON string with the task output (e.g. {"response": ..., "output": ...}). |
Return:
bool - Returns true if the task was updated.
Throws:
- Luminova\Exceptions\RuntimeException - If the status or filter is invalid.
clean
Release the lock and delete the stop signal file if it exists.
protected final function clean(): voidisConnected
Check if the database connection is active and ready.
protected final function isConnected(): boolReturn:
bool - Returns true if connected, otherwise false.
out
Output a worker status message. By default the message is printed with echo. Override it to change where worker messages go.
protected function out(string $message): voidexportResult
Convert a task result to a value that can be saved in the database.
- Scalars (int, float, bool, string) and
null: returned as is - Resources: returned as a string with the resource type
- Arrays and objects: JSON encoded
- Anything else:
var_exportrepresentation
Override this method to change how task responses are exported.
protected function exportResult(mixed $result): string|int|float|bool|nullParameters:
| Parameter | Type | Description |
|---|---|---|
$result | mixed | The value to export. |
Return:
string|int|float|bool|null - Returns the exported result.
getCallable
Resolve a handler string into a PHP callable.
Supported handler formats:
Class@method: Creates the class instance and calls the method.Class::method: Static method call.Class: Creates the class instance if it exists.function_name: Uses the function if it exists.- A serialized closure: Restored with its serializer.
protected function getCallable(
string $handler,
bool &$isInvokable = false,
bool &$isQueueable = false,
bool &$isWorker = false,
bool &$isAutoDelete = false
): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$handler | string | The handler string to resolve. |
$isInvokable | bool | Set to true if the instance implements InvokableInterface. |
$isQueueable | bool | Set to true if the instance implements QueueableInterface. |
$isWorker | bool | Set to true if the instance implements TaskWorkerInterface and received the command input. |
$isAutoDelete | bool | Set to true if a queueable instance asks to be deleted on completion. |
Return:
callable|null - Returns a callable, or null if the handler cannot be resolved.
Override this method to change how handlers are resolved before execution.
toDateTime
Normalize a schedule value to a Y-m-d H:i:s string.
protected final function toDateTime(mixed $value): ?stringReturn:
string|null - Returns the datetime string, or null if the value is empty or cannot be parsed.
getForever
Validate the forever interval.
protected final function getForever(mixed $forever): ?intReturn:
int|null - Returns the interval in minutes, or null if not set.
Throws:
- Luminova\Exceptions\InvalidArgumentException - If the value is not numeric or is less than 5 minutes.
database
Get the active database driver.
protected final function database(): DatabaseDriverInterfaceThrows:
- Luminova\Exceptions\DatabaseException - If the database is not connected.
Task Model
Luminova\Models\Task represents a single queued task. The queue returns it from get() by default. Set $returnAsTaskModel to false to get associative arrays, as the Novakit worker does.
| Property | Type | Description |
|---|---|---|
$id | int | Task ID. |
$priority | int | Execution priority (0 = highest, 100 = lowest). |
$attempts | int | Number of execution attempts. |
$retries | int | Maximum retries after a failure. |
$forever | int|null | Run interval in minutes for forever tasks. |
$status | string | Current task status. |
$group_name | string | Task group name. |
$handler | string | Task handler. |
$arguments | array|string|null | Handler arguments. Use getArguments() to always get an array. |
$signature | string | XXH3 signature of the handler and arguments. |
$outputs | array|string|null | Execution response and output. Use getOutputs() to always get an array. |
$scheduled_at | string|null | Datetime the task is delayed until. |
$created_at | string | Datetime the task was queued. |
$updated_at | string|null | Datetime of the last execution or update. |
$auto_delete | int | 1 if the task is deleted on completion. |
| Method | Description |
|---|---|
__construct(?array $task = null, ?AbstractTaskQueue $system = null) | Create a task, optionally from an array and a queue system (defaults to App\Tasks\TaskQueue). |
setSystem(AbstractTaskQueue $system): self | Set the queue system used to manage the task. |
fromArray(array $task): self | Populate the task from an associative array. |
enqueue(): bool | Queue this task using its handler, arguments, priority, forever and retries values. |
retry(): bool | Retry the task. |
pause(): bool | Pause the task. |
delete(): bool | Delete the task. |
getArguments(): array | Get the handler arguments as an array. |
getOutputs(): array | Get the output as ['response' => mixed, 'output' => string]. |
getResponse(): mixed | Get the handler response. |
getOutput(): mixed | Get the captured output or error message. |
isDue(): bool | Check if the task is due based on its schedule. |
isExecutable(): bool | Check if the task can run now. |
isRetryable(): bool | Check if the task can be retried. |
isAutoDelete(): bool | Check if the task is deleted on completion. |
isClosure(): bool | Check if the handler is a serialized closure. |
isStatus(array|string $status): bool | Check if the task status matches one or any of the given statuses. |
Background Task Comparison
Luminova\Base\AbstractTaskScheduler vs. Luminova\Base\AbstractTaskQueue
AbstractTaskScheduler (Filesystem Scheduler)
Designed for static, cron style scheduling with tasks defined in a class.
Task definitions are file based, no database required.
No support for adding tasks dynamically from code.
Commands:
cron:createto register and lock the defined tasks.cron:runto execute due tasks.
Good for simple, predictable schedules but not flexible.
Limitations:
- Static schedules only.
- Cannot schedule tasks dynamically at runtime.
- No runtime state tracking or fine grained control.
TaskQueue (Database Task Manager)
Supports code defined tasks using
enqueue()andbatchEnqueue(), or the CLI.Supports delayed execution with a
schedulevalue: a timestamp, aDateTimeor a relative time (+5 minutes,tomorrow).Tasks are stored in the database, with status, attempts, output and retries tracked per task.
Runtime management features:
- File locks to prevent double execution.
- Signal handling for clean termination.
- Status monitoring through the CLI and event logs.
CLI Commands:
task:queueto enqueue a task.task:runto run due tasks.task:list,task:purge,task:tailand more for queue management.