Luminova Framework

PHP Luminova: Database Queue for Background Tasks

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

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\AbstractTaskScheduler works, but it's rigid.If you need dynamic, programmatic task scheduling, runtime safety, and monitoring, Luminova\Base\AbstractTaskQueue is 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()and ON 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: sendEmail

  • A static methodExample: App\Utils\Worker::process

  • A class and method using instance styleExample: App\Utils\Worker@clean

  • A [class, method] array, which is converted to the static format (Class::method). The method must exist, otherwise a RuntimeException is thrown.Example: [App\Utils\Worker::class, 'process']

  • An invokable class that implements Luminova\Interface\InvokableInterface or Luminova\Interface\QueueableInterfaceExample: App\Utils\Worker

  • An anonymous class or closure serialized with Luminova\Utility\Serializer or Opis\Closure\SerializerAnonymous classes must implement QueueableInterface and define __invoke().

Note:

The $isClosureSupported property enables the isClosure() check for serialized handlers.The default App\Tasks\TaskQueue class sets it to true.


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:init

After 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@run

Ensuring 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:

  1. Success: Let the handler finish without throwing an exception. A task that finishes is marked completed, whatever it returns.
  2. Failure: Throw an exception for any failure. The task is marked failed and the exception message is saved as its output.
  3. Retries: A failed task runs again only when it was queued with retries greater than zero, and only until its attempts reach that limit. With the default of 0, it stays failed until you call retry().

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, has retries greater than zero, and its attempts are below that limit.
  • It is a forever task whose status is pending, failed or completed, and its last update is at least forever minutes 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 $deleteOnCompletion to true.
  • The handler implements QueueableInterface and deleteOnCompletion() returns true.

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

ConstantTypeDescription
PENDINGstringTask is waiting to be picked up by the worker.
PAUSEDstringTask is paused and will not run until resumed.
RUNNINGstringTask is currently being processed.
FAILEDstringTask execution failed. Usually caused by an exception.
COMPLETEDstringTask finished successfully and may be deleted if configured.

Task Result Filters

ConstantVisibilityTypeDescription
ALLpublicstringMatches tasks of all statuses.
FOREVERpublicstringMatches tasks scheduled to run repeatedly, which are never auto-removed.
EXCEPTIONprotectedstringIdentifies tasks whose handler could not be resolved or called.
PAUSEABLEprotectedstringMatches tasks that can be paused (pending or failed).
EXECUTABLEprotectedstringMatches 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 call parent::__construct()or use onCreate() 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(): static

Return:

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): mixed

Parameters:

ParameterTypeDescription
$methodstringThe method name.
$argumentsarray<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(): void

Example:

// /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(): ?array

Each task is an associative array with the following keys:

  • handler (string, required): A valid handler, such as Class@method, Class::method, or function_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. 1440 for 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
): self

Parameters:

ParameterTypeDescription
$handlerarray<array-key, mixed>&#124;stringThe task handler reference (e.g. function name, Class@method, Class::method, or an invokable class).
$argumentsarray<array-key, mixed>Optional arguments to pass to the task on execution.
$scheduleDateTimeInterface|string|int|nullOptional delay for task execution (default: null).
$priorityintOptional priority (0 = highest, 100 = lowest) (default: 0).
$foreverint|nullOptional interval in minutes for repeated execution (e.g. 1440 = once per day).
$retriesintNumber of times to retry the task if it fails (default: 0, no retry).
$deleteOnCompleteboolIf 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 the scheduled_at key. The $schedule value stored by stage() 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(): array

Return:

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
): int

Parameters:

ParameterTypeDescription
$handlerarray<array-key, mixed>&#124;stringThe 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.
$argumentsarray<array-key, mixed>Optional arguments to pass to the handler on execution. They are stored as an ordered list.
$scheduleDateTimeInterface|string|int|nullOptional delay for task execution (default: null).
Accepts DateTime, Unix timestamp, or relative time.
If null or not parseable, the task is due immediately.
$priorityintOptional priority (0 = highest, 100 = lowest). Values outside the range are clamped. Default is 0.
$foreverint|nullInterval in minutes between repeated executions for a forever task (default: null).
Must be 5 or more (e.g. 1440 = once per day).
$retriesintNumber of times to retry the task if it fails (default: 0, no retry).
$deleteOnCompleteboolIf 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:

Note: Each task gets a signature from its handler and arguments. Queuing the same handler and arguments again resets the matching task to pending and 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@method or function_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): int

Parameters:

ParameterTypeDescription
$tasksarray<int, array<string, mixed>|Task>Array of task definitions.

Return:

int - Returns the number of tasks inserted.

Throws:

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 needs pcntl and CLI mode.
  • The stop signal file is detected (only when $stopSignalFile is 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
): void

Parameters:

ParameterTypeDescription
$sleepfloat|intBase delay between task cycles. Novakit passes an integer in microseconds (default 100000).
$limitint|nullMaximum number of tasks to fetch per cycle. null for no limit.
$maxIdleintMaximum consecutive idle cycles before the worker shuts down (default: 10).
$idint|nullOptional task ID to run only that task.

Throws:

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): void

Parameters:

ParameterTypeDescription
$signalint|nullOptional 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(): array

Return:

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|null

Parameters:

ParameterTypeDescription
$idintThe 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:


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
): ?array

Parameters:

ParameterTypeDescription
$statusstringTask status to filter by. Use all for every status (default: all).
$limitint|nullMaximum number of tasks to retrieve. null for no limit (default: null).
$offsetintThe offset to start from (default: 0).
$withTotalboolWhether 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 $withTotal is true, the structure is ['total' => int, 'count' => int, 'tasks' => array].

Throws:


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
): ?array

Parameters:

ParameterTypeDescription
$idint|nullTask ID to find. If null, multiple tasks are returned.
$statusstringStatus to filter by. Accepts all, forever, executable or a task status (default: all).
$limitint|nullMaximum number of tasks to retrieve (default: null).
$offsetintThe offset to start from (default: 0).
$withTotalboolWhether 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:


count

Count the tasks matching a given status.

public function count(string $status = self::ALL): int

Parameters:

ParameterTypeDescription
$statusstringTask status to count (e.g. pending, failed, all).
Also accepts forever and executable.

Return:

int - Returns the number of matching tasks.

Throws:


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): bool

Parameters:

ParameterTypeDescription
$idintThe task ID.
$newStatusstringThe new status.

Return:

bool - Returns true if the task was updated.

Throws:


retry

Reset a failed task back to pending. Only tasks currently failed are changed.

public function retry(int $id): bool

Parameters:

ParameterTypeDescription
$idintThe task ID to retry.

Return:

bool - Returns true if the task was updated.

Throws:


pause

Pause a task by setting its status to paused, only if it is currently pending or failed.

public function pause(int $id): bool

Parameters:

ParameterTypeDescription
$idintThe task ID to pause.

Return:

bool - Returns true if the task was paused, otherwise false.

Throws:


resume

Resume a paused task by setting its status to pending.

public function resume(int $id): bool

Parameters:

ParameterTypeDescription
$idintThe task ID to resume.

Return:

bool - Returns true if the task was resumed, otherwise false.

Throws:


delete

Delete a task by ID within the current group.

public function delete(int $id): bool

Parameters:

ParameterTypeDescription
$idintThe task ID to delete.

Return:

bool - Returns true if the task was deleted.

Throws:


purge

Delete all tasks of the current group with a given status.

public function purge(string $status = self::ALL): int

Parameters:

ParameterTypeDescription
$statusstringStatus to match. Use all to delete everything, or forever to delete forever tasks.

Return:

int - Returns the number of tasks deleted.

Throws:


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): bool

Parameters:

ParameterTypeDescription
$statusstringTask status to filter by (default: all).
$pathstring|nullOptional path to write the exported file. Updated with the final path.
$metadatastring|nullOptional 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:


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(): bool

Return:

bool - Returns true if the table was created or already exists.

Throws:


isInitialized

Check if the task database table exists.

public function isInitialized(): bool

Return:

bool - Returns true if the table exists.

Throws:


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(): bool

Return:

bool - Returns true if the table was dropped.

Throws:


close

Close the active database connection, if connected.

public function close(): bool

Return:

bool - Returns true if the connection was closed, false otherwise.


isLocked

Check if the task worker is currently locked.

public function isLocked(): bool

Return:

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): bool

Parameters:

ParameterTypeDescription
$permissionint|nullDirectory 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(): bool

Return:

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): bool

Parameters:

ParameterTypeDescription
$handlerstringThe 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): ?string

Parameters:

ParameterTypeDescription
$handlerstringThe 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): array

Parameters:

ParameterTypeDescription
$handlerstringThe 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(): string

Return:

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 $taskEventTailing to be true.
  • signal: The stop and resume signal file. Requires $stopSignalFile to be set.
  • flock: The lock file that prevents duplicate workers.
public function getPathInfo(string $context): ?array

Parameters:

ParameterTypeDescription
$contextstringOne 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): self

Parameters:

ParameterTypeDescription
$inputInputThe 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
): bool

Parameters:

ParameterTypeDescription
$idintTask ID.
$statusstringNew status to set.
$filterstring|nullOnly update when the current status matches this.
Special values: pauseable allows pending and failed, forever allows forever tasks.
$outputsstring|nullOptional JSON string with the task output (e.g. {"response": ..., "output": ...}).

Return:

bool - Returns true if the task was updated.

Throws:


clean

Release the lock and delete the stop signal file if it exists.

protected final function clean(): void

isConnected

Check if the database connection is active and ready.

protected final function isConnected(): bool

Return:

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): void

exportResult

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_export representation

Override this method to change how task responses are exported.

protected function exportResult(mixed $result): string|int|float|bool|null

Parameters:

ParameterTypeDescription
$resultmixedThe 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
): mixed

Parameters:

ParameterTypeDescription
$handlerstringThe handler string to resolve.
$isInvokableboolSet to true if the instance implements InvokableInterface.
$isQueueableboolSet to true if the instance implements QueueableInterface.
$isWorkerboolSet to true if the instance implements TaskWorkerInterface and received the command input.
$isAutoDeleteboolSet 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): ?string

Return:

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): ?int

Return:

int|null - Returns the interval in minutes, or null if not set.

Throws:


database

Get the active database driver.

protected final function database(): DatabaseDriverInterface

Throws:


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.

PropertyTypeDescription
$idintTask ID.
$priorityintExecution priority (0 = highest, 100 = lowest).
$attemptsintNumber of execution attempts.
$retriesintMaximum retries after a failure.
$foreverint|nullRun interval in minutes for forever tasks.
$statusstringCurrent task status.
$group_namestringTask group name.
$handlerstringTask handler.
$argumentsarray|string|nullHandler arguments. Use getArguments() to always get an array.
$signaturestringXXH3 signature of the handler and arguments.
$outputsarray|string|nullExecution response and output. Use getOutputs() to always get an array.
$scheduled_atstring|nullDatetime the task is delayed until.
$created_atstringDatetime the task was queued.
$updated_atstring|nullDatetime of the last execution or update.
$auto_deleteint1 if the task is deleted on completion.
MethodDescription
__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): selfSet the queue system used to manage the task.
fromArray(array $task): selfPopulate the task from an associative array.
enqueue(): boolQueue this task using its handler, arguments, priority, forever and retries values.
retry(): boolRetry the task.
pause(): boolPause the task.
delete(): boolDelete the task.
getArguments(): arrayGet the handler arguments as an array.
getOutputs(): arrayGet the output as ['response' => mixed, 'output' => string].
getResponse(): mixedGet the handler response.
getOutput(): mixedGet the captured output or error message.
isDue(): boolCheck if the task is due based on its schedule.
isExecutable(): boolCheck if the task can run now.
isRetryable(): boolCheck if the task can be retried.
isAutoDelete(): boolCheck if the task is deleted on completion.
isClosure(): boolCheck if the handler is a serialized closure.
isStatus(array&#124;string $status): boolCheck 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:create to register and lock the defined tasks.
    • cron:run to 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() and batchEnqueue(), or the CLI.

  • Supports delayed execution with a schedule value: a timestamp, a DateTime or 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:queue to enqueue a task.
  • task:run to run due tasks.
  • task:list, task:purge, task:tail and more for queue management.