rafalmasiarek / dashboard-kit-addon-scheduler
Scheduler addon for rafalmasiarek/dashboard-kit. Cron-expression task runner with queue+redirect anti-timeout, file/PDO state stores and /cron HTTP endpoints.
Package info
github.com/rafalmasiarek/php-dashboard-kit-addon-scheduler
pkg:composer/rafalmasiarek/dashboard-kit-addon-scheduler
Requires
- php: >=8.2
- dragonmantank/cron-expression: ^3.3
- rafalmasiarek/dashboard-kit: >=5.0
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-17 23:37:10 UTC
README
Cron-expression task scheduler addon for rafalmasiarek/dashboard-kit.
Auto-discovers tasks from module schedule definitions. Runs tasks via HTTP endpoints with a queue+redirect mechanism to avoid PHP execution timeouts on long-running jobs.
License
Business Source License 1.1.
Source available; commercial use restricted until 2099-01-01.
See LICENSE for full details.
For alternative licensing, contact us.
Authors
Requirements
- PHP 8.2+
rafalmasiarek/dashboard-kit: *
Installation
composer require rafalmasiarek/dashboard-kit-addon-scheduler
Quick start
use rafalmasiarek\DashboardKitScheduler\SchedulerAddon; $dashboard = Dashboard::create(__DIR__ . '/../', [ 'scheduler' => [ 'token' => $_ENV['SCHEDULER_TOKEN'], ], ]); SchedulerAddon::register($dashboard->getApp(), $dashboard->getContainer()); $dashboard->run();
Configuration
| Key | Default | Description |
|---|---|---|
endpoint |
true |
Register native HTTP endpoints (/scheduler/status, /scheduler/run, /scheduler/job) |
prefix |
'' |
URL prefix prepended to all endpoints (e.g. '/v1') |
token |
SCHEDULER_TOKEN env |
Bearer token required on GET /scheduler/run |
Config can be passed as the third argument to register() or via app.config['scheduler'] in Dashboard::create().
HTTP endpoints
| Endpoint | Auth | Description |
|---|---|---|
GET /scheduler/status |
none | Lists all tasks with last_run_at and is_due |
GET /scheduler/run |
Bearer token | Runs due tasks; queues long-running ones and redirects |
GET /scheduler/job |
queue token | Executes one step of a queued task (internal) |
Trigger from a system cron:
* * * * * curl -s -H "Authorization: Bearer $TOKEN" https://example.com/scheduler/run
Module schedule format
Add a schedule key to any module's module.php:
return [ 'title' => 'Notes', 'icon' => 'π', 'schedule' => [ [ 'id' => 'cleanup', 'cron' => '0 3 * * *', 'action' => 'callable', 'options' => [ 'handler' => function (\rafalmasiarek\DashboardKitScheduler\TaskContext $ctx): void { // runs at 03:00 every day }, ], ], ], 'render' => function ($req, $res, $args, $twig, $db, $container) { ... }, ];
The global task ID will be notes.cleanup. Tasks appear in /scheduler/status.
Task definition keys
| Key | Required | Description |
|---|---|---|
id |
yes | Local task ID (prefixed with module slug for the global ID) |
cron |
yes | Cron expression (5-field, e.g. '*/5 * * * *') |
action |
yes | Factory action name. Built-in: 'callable' |
options |
no | Action-specific options. For callable: handler (PHP callable or 'Class@method') |
enabled |
no | false disables the task without removing it (default: true) |
allow_parallel |
no | Allow concurrent runs (default: false) |
Built-in cleanup task
__scheduler.cleanup runs daily at 03:15 and removes queue files older than 24 hours from storage/cron_queues/. It is registered automatically β no configuration needed.
Monitoring
The plugin provides MonitoringInterface and NoopMonitoring (default). To wire a custom implementation:
use rafalmasiarek\DashboardKitScheduler\MonitoringInterface; // Set before $dashboard->run() β resolved lazily when Scheduler is first used $dashboard->getContainer()->set(MonitoringInterface::class, static fn() => new MyMonitoring([ 'my-module.my-task' => ['url' => 'https://hc-ping.com/your-uuid'], ]));
Or read from app.config (config lives alongside other scheduler settings):
$container = $dashboard->getContainer(); $container->set(MonitoringInterface::class, static function () use ($container) { $cfg = (array) ($container->get('app.config')['scheduler']['monitoring']['healthchecks'] ?? []); return new MyMonitoring($cfg); });
MyMonitoring must implement rafalmasiarek\DashboardKitScheduler\MonitoringInterface:
interface MonitoringInterface { public function onTaskRunStart(string $taskId, array $context = []): void; public function onTaskRunOk(string $taskId, array $record, array $ctx): void; public function onTaskRunFail(string $taskId, array $record, \Throwable $e, array $ctx): void; }
All methods must swallow their own exceptions β monitoring must never break scheduling.
Disabling native endpoints
When endpoint: false, only Scheduler::class and QueueManager::class are registered in the container. Use this when building custom routes with your own auth (e.g. via dashboard-kit-addon-api token scopes).
SchedulerAddon::register($dashboard->getApp(), $dashboard->getContainer(), [ 'endpoint' => false, ]);
Index
Classes
CompositeMonitoringβrafalmasiarek\DashboardKitSchedulerTaskLockedExceptionβrafalmasiarek\DashboardKitScheduler\ExceptionFileStateStoreβrafalmasiarek\DashboardKitSchedulerJobHandlerβrafalmasiarek\DashboardKitScheduler\HttpJsonResponderβrafalmasiarek\DashboardKitScheduler\HttpQueueManagerβrafalmasiarek\DashboardKitScheduler\HttpRunHandlerβrafalmasiarek\DashboardKitScheduler\HttpStatusHandlerβrafalmasiarek\DashboardKitScheduler\HttpProcessFileLockβrafalmasiarek\DashboardKitScheduler\LockFileLockMiddlewareβrafalmasiarek\DashboardKitScheduler\MiddlewareNoopMonitoringβrafalmasiarek\DashboardKitSchedulerAbstractOutputPolicyβrafalmasiarek\DashboardKitScheduler\OutputCronOutputBuilderβrafalmasiarek\DashboardKitScheduler\OutputDefaultOutputPolicyβrafalmasiarek\DashboardKitScheduler\OutputOutputPolicyResolverβrafalmasiarek\DashboardKitScheduler\OutputPdoStateStoreβrafalmasiarek\DashboardKitSchedulerQueuePayloadβrafalmasiarek\DashboardKitSchedulerSchedulerβrafalmasiarek\DashboardKitSchedulerSchedulerAddonβrafalmasiarek\DashboardKitSchedulerSchedulerSchemaProviderβrafalmasiarek\DashboardKitScheduler\SchemaSystemLogMonitoringβrafalmasiarek\DashboardKitSchedulerCallableTaskFactoryβrafalmasiarek\DashboardKitScheduler\Task\BuiltinTaskRegistryβrafalmasiarek\DashboardKitScheduler\TaskTaskContextβrafalmasiarek\DashboardKitScheduler
Interfaces
MonitoringInterfaceβrafalmasiarek\DashboardKitSchedulerOutputPolicyInterfaceβrafalmasiarek\DashboardKitScheduler\OutputSchedulerStateStoreβrafalmasiarek\DashboardKitSchedulerTaskFactoryInterfaceβrafalmasiarek\DashboardKitScheduler\TaskTaskMiddlewareInterfaceβrafalmasiarek\DashboardKitScheduler
CompositeMonitoring
final class β rafalmasiarek\DashboardKitScheduler\CompositeMonitoring Β· source
Delegates monitoring events to multiple MonitoringInterface implementations. Used internally by SchedulerAddon to chain SystemLogMonitoring with any user-supplied MonitoringInterface binding, so both receive every lifecycle event. Each delegate's exceptions are suppressed individually so one failing monitor cannot prevent others from being called.
implements MonitoringInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | β | β |
onTaskRunStart() |
public | void |
Called right before running a task. |
onTaskRunOk() |
public | void |
Called after a successful task run. |
onTaskRunFail() |
public | void |
Called after a failed task run. |
__construct()
CompositeMonitoring __construct()
public function __construct(array $monitors)
| Param | Type | Description |
|---|---|---|
$monitors |
MonitoringInterface[] |
Ordered list of monitors to invoke. |
onTaskRunStart()
CompositeMonitoring onTaskRunStart()
public function onTaskRunStart(string $taskId, array $context): void
Called right before running a task.
| Param | Type | Description |
|---|---|---|
$taskId |
string |
β |
$context |
array<string, mixed> |
β |
onTaskRunOk()
CompositeMonitoring onTaskRunOk()
public function onTaskRunOk(string $taskId, array $record, array $ctx): void
Called after a successful task run.
| Param | Type | Description |
|---|---|---|
$taskId |
string |
β |
$record |
array<string, mixed> |
Full task run record from Scheduler::runTask(). |
$ctx |
array<string, mixed> |
β |
onTaskRunFail()
CompositeMonitoring onTaskRunFail()
public function onTaskRunFail(string $taskId, array $record, \Throwable $e, array $ctx): void
Called after a failed task run.
| Param | Type | Description |
|---|---|---|
$taskId |
string |
β |
$record |
array<string, mixed> |
Full task run record from Scheduler::runTask(). |
$e |
\Throwable |
Exception thrown by the task. |
$ctx |
array<string, mixed> |
β |
TaskLockedException
final class β rafalmasiarek\DashboardKitScheduler\Exception\TaskLockedException Β· source
Thrown when a task's file lock cannot be acquired.
extends \RuntimeException
Package: rafalmasiarek\DashboardKitScheduler
FileStateStore
final class β rafalmasiarek\DashboardKitScheduler\FileStateStore Β· source
File-based implementation of SchedulerStateStore. Each key is stored as a separate file in the given directory.
implements SchedulerStateStore
| Property | Type | Visibility | Description |
|---|---|---|---|
$dir |
string |
private | β |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | β | β |
read() |
public | string|null |
Read a value by key. |
write() |
public | void |
Write a value by key. |
delete() |
public | void |
Delete a value by key. |
__construct()
FileStateStore __construct()
public function __construct(string $dir)
| Param | Type | Description |
|---|---|---|
$dir |
string |
Directory path for state files (created automatically if missing). |
read()
FileStateStore read()
public function read(string $key): ?string
Read a value by key.
| Param | Type | Description |
|---|---|---|
$key |
string |
β |
Returns: string\|null
write()
FileStateStore write()
public function write(string $key, string $value): void
Write a value by key.
| Param | Type | Description |
|---|---|---|
$key |
string |
β |
$value |
string |
β |
delete()
FileStateStore delete()
public function delete(string $key): void
Delete a value by key.
| Param | Type | Description |
|---|---|---|
$key |
string |
β |
JobHandler
final class β rafalmasiarek\DashboardKitScheduler\Http\JobHandler Β· source
GET /cron/job β internal endpoint (queue token required). Executes one task step from a queue created by RunHandler. After execution either: - 303-redirects to the next part of the same task (multi-part), - 303-redirects to the next pending task in the queue, - returns 200 with "Cron queue completed." when all tasks are done.
Depends on: Scheduler, ClockInterface, QueueManager
Package: rafalmasiarek\DashboardKitScheduler
| Property | Type | Visibility | Description |
|---|---|---|---|
$scheduler |
Scheduler |
private | β |
$clock |
ClockInterface |
private | β |
$queueManager |
QueueManager |
private | β |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | β | β |
__invoke() |
public | ResponseInterface |
Handle a single job step from a queue. |
__construct()
JobHandler __construct()
public function __construct(Scheduler $scheduler, ClockInterface $clock, QueueManager $queueManager)
| Param | Type | Description |
|---|---|---|
$scheduler |
Scheduler |
β |
$clock |
ClockInterface |
β |
$queueManager |
QueueManager |
β |
__invoke()
JobHandler __invoke()
public function __invoke(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
Handle a single job step from a queue.
| Param | Type | Description |
|---|---|---|
$request |
ServerRequestInterface |
β |
$response |
ResponseInterface |
β |
Returns: ResponseInterface
JsonResponder
final class β rafalmasiarek\DashboardKitScheduler\Http\JsonResponder Β· source
Minimal JSON response builder for scheduler HTTP endpoints. Wraps responses in the same envelope as api.masiarek.pl's JsonHandler so that the output is structurally compatible when migrating.
Package: rafalmasiarek\DashboardKitScheduler
| Method | Visibility | Returns | Summary |
|---|---|---|---|
ok() |
public static | ResponseInterface |
Write a successful JSON response. |
error() |
public static | ResponseInterface |
Write an error JSON response. |
ok()
JsonResponder ok()
public static function ok(ResponseInterface $response, string $message, array $data, int $status): ResponseInterface
Write a successful JSON response.
| Param | Type | Description |
|---|---|---|
$response |
ResponseInterface |
β |
$message |
string |
β |
$data |
array<string, mixed> |
β |
$status |
int |
β |
Returns: ResponseInterface
error()
JsonResponder error()
public static function error(ResponseInterface $response, string $message, int $status, ?string $error): ResponseInterface
Write an error JSON response.
| Param | Type | Description |
|---|---|---|
$response |
ResponseInterface |
β |
$message |
string |
β |
$status |
int |
β |
$error |
string|null |
Machine-readable error code. |
Returns: ResponseInterface
QueueManager
final class β rafalmasiarek\DashboardKitScheduler\Http\QueueManager Β· source
Manages cron queue files used by the queue+redirect anti-timeout mechanism. Each queue is a JSON file in the cron_queues directory. All mutations are serialized via an advisory flock on a ".json.lock" file, matching the convention used by QueuePayload.
Package: rafalmasiarek\DashboardKitScheduler
| Property | Type | Visibility | Description |
|---|---|---|---|
$dir |
string |
private | β |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | β | β |
dir() |
public | string |
Return the queue directory path. |
path() |
public | string |
Return the absolute path for a queue JSON file. |
create() |
public | array<string, mixed> |
Create and persist a new queue file. |
load() |
public | array<string, mixed>|null |
Load a queue file. |
save() |
public | void |
Persist a queue file. |
validateToken() |
public | array<string, mixed>|null |
Validate a queue token and return the queue if valid. |
withLock() |
public | T |
Execute callback while holding an exclusive lock on the queue file. |
filterPassthrough() |
public static | array<string, string> |
Remove internal queue/routing params from query params; normalize values to strings. |
buildPassthroughQs() |
public static | string |
Build a "&"-prefixed query string from pass-through params. |
exportToServer() |
public static | void |
Export pass-through params into $SERVER as CRON_JOB* variables. |
__construct()
QueueManager __construct()
public function __construct(string $storageDir)
| Param | Type | Description |
|---|---|---|
$storageDir |
string |
Base storage directory (e.g. "/storage"). |
dir()
QueueManager dir()
public function dir(): string
Return the queue directory path.
Returns: string
path()
QueueManager path()
public function path(string $id): string
Return the absolute path for a queue JSON file.
| Param | Type | Description |
|---|---|---|
$id |
string |
β |
Returns: string
create()
QueueManager create()
public function create(string $id, string $secret, array $tasks, array $passthroughQuery, ClockInterface $clock, array $runIdsByTask): array
Create and persist a new queue file.
| Param | Type | Description |
|---|---|---|
$id |
string |
β |
$secret |
string |
β |
$tasks |
string[] |
β |
$passthroughQuery |
array<string, string> |
β |
$clock |
ClockInterface |
β |
$runIdsByTask |
array<string, string> |
Optional run_id per task name. |
Returns: array<string, mixed>
load()
QueueManager load()
public function load(string $id): ?array
Load a queue file.
| Param | Type | Description |
|---|---|---|
$id |
string |
β |
Returns: array<string, mixed>\|null
save()
QueueManager save()
public function save(array $queue): void
Persist a queue file.
| Param | Type | Description |
|---|---|---|
$queue |
array<string, mixed> |
β |
validateToken()
QueueManager validateToken()
public function validateToken(string $queueId, string $token): ?array
Validate a queue token and return the queue if valid.
| Param | Type | Description |
|---|---|---|
$queueId |
string |
β |
$token |
string |
β |
Returns: array<string, mixed>\|null
withLock()
QueueManager withLock()
public function withLock(string $id, callable $fn):
Execute callback while holding an exclusive lock on the queue file.
| Param | Type | Description |
|---|---|---|
$id |
string |
Queue ID. |
$fn |
callable(): T |
β |
Returns: T
filterPassthrough()
QueueManager filterPassthrough()
public static function filterPassthrough(array $q): array
Remove internal queue/routing params from query params; normalize values to strings.
| Param | Type | Description |
|---|---|---|
$q |
array<string, mixed> |
β |
Returns: array<string, string>
buildPassthroughQs()
QueueManager buildPassthroughQs()
public static function buildPassthroughQs(array $passthrough): string
Build a "&"-prefixed query string from pass-through params.
| Param | Type | Description |
|---|---|---|
$passthrough |
array<string, string> |
β |
Returns: string
exportToServer()
QueueManager exportToServer()
public static function exportToServer(array $passthrough): void
Export pass-through params into $SERVER as CRON_JOB* variables.
| Param | Type | Description |
|---|---|---|
$passthrough |
array<string, string> |
β |
RunHandler
final class β rafalmasiarek\DashboardKitScheduler\Http\RunHandler Β· source
GET /cron β authenticated endpoint (SCHEDULER_TOKEN or Bearer). Without ?task=: discovers due tasks, creates a queue and 303-redirects to /cron/job. With ?task=: runs a single task directly; if the task signals multi-part continuation (next_part != null in result) or queue-init mode (queue_init=true), creates a queue and 303-redirects to /cron/job. Pass-through: all query params except queue/qt/index/part are forwarded to all /cron/job calls.
Depends on: Scheduler, ClockInterface, QueueManager
Package: rafalmasiarek\DashboardKitScheduler
| Property | Type | Visibility | Description |
|---|---|---|---|
$scheduler |
Scheduler |
private | β |
$clock |
ClockInterface |
private | β |
$queueManager |
QueueManager |
private | β |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | β | β |
__invoke() |
public | ResponseInterface |
Handle the run request. |
runSingleTask() |
private | ResponseInterface |
Run a single named task, handling queue-init and continuation modes. |
createQueue() |
private | ResponseInterface |
Create a queue for a single task and redirect to the first job. |
isQueueInit() |
private | bool |
Detect queue-init result: task returns ['queue_init' => true, 'total_parts' => N>=2]. |
jobPath() |
private | string |
Derive the /cron/job URL path from the current request. |
qBool() |
private | bool|null |
Read a boolean-ish query parameter. |
__construct()
RunHandler __construct()
public function __construct(Scheduler $scheduler, ClockInterface $clock, QueueManager $queueManager)
| Param | Type | Description |
|---|---|---|
$scheduler |
Scheduler |
β |
$clock |
ClockInterface |
β |
$queueManager |
QueueManager |
β |
__invoke()
RunHandler __invoke()
public function __invoke(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
Handle the run request.
| Param | Type | Description |
|---|---|---|
$request |
ServerRequestInterface |
β |
$response |
ResponseInterface |
β |
Returns: ResponseInterface
runSingleTask()
RunHandler runSingleTask()
private function runSingleTask(ServerRequestInterface $request, ResponseInterface $response, string $taskId, bool $force, array $passthrough, string $passQs, array $options): ResponseInterface
Run a single named task, handling queue-init and continuation modes.
| Param | Type | Description |
|---|---|---|
$request |
ServerRequestInterface |
β |
$response |
ResponseInterface |
β |
$taskId |
string |
β |
$force |
bool |
β |
$passthrough |
array<string, string> |
β |
$passQs |
string |
β |
$options |
array<string, mixed> |
Output options (e.g. ['verbose' => true]). |
Returns: ResponseInterface
createQueue()
RunHandler createQueue()
private function createQueue(ServerRequestInterface $request, ResponseInterface $response, string $taskId, string $runId, array $passthrough, string $passQs, int $firstPart, array $initialRecord, string $message, array $options): ResponseInterface
Create a queue for a single task and redirect to the first job.
| Param | Type | Description |
|---|---|---|
$request |
ServerRequestInterface |
β |
$response |
ResponseInterface |
β |
$taskId |
string |
β |
$runId |
string |
β |
$passthrough |
array<string, string> |
β |
$passQs |
string |
β |
$firstPart |
int |
β |
$initialRecord |
array<string, mixed> |
β |
$message |
string |
β |
$options |
array<string, mixed> |
Output options (e.g. ['verbose' => true]). |
Returns: ResponseInterface
isQueueInit()
RunHandler isQueueInit()
private function isQueueInit(?array $result): bool
Detect queue-init result: task returns ['queue_init' => true, 'total_parts' => N>=2].
| Param | Type | Description |
|---|---|---|
$result |
array<string, mixed>|null |
β |
Returns: bool
jobPath()
RunHandler jobPath()
private function jobPath(ServerRequestInterface $request): string
Derive the /cron/job URL path from the current request.
| Param | Type | Description |
|---|---|---|
$request |
ServerRequestInterface |
β |
Returns: string
qBool()
RunHandler qBool()
private function qBool(array $q, string $key): ?bool
Read a boolean-ish query parameter.
| Param | Type | Description |
|---|---|---|
$q |
array<string, mixed> |
β |
$key |
string |
β |
Returns: bool\|null
StatusHandler
final class β rafalmasiarek\DashboardKitScheduler\Http\StatusHandler Β· source
GET /cron/status β public endpoint. Lists all registered tasks with their cron expression, last_run_at and is_due flag.
Depends on: Scheduler, ClockInterface
Package: rafalmasiarek\DashboardKitScheduler
| Property | Type | Visibility | Description |
|---|---|---|---|
$scheduler |
Scheduler |
private | β |
$clock |
ClockInterface |
private | β |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | β | β |
__invoke() |
public | ResponseInterface |
Handle the status request. |
__construct()
StatusHandler __construct()
public function __construct(Scheduler $scheduler, ClockInterface $clock)
| Param | Type | Description |
|---|---|---|
$scheduler |
Scheduler |
β |
$clock |
ClockInterface |
β |
__invoke()
StatusHandler __invoke()
public function __invoke(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
Handle the status request.
| Param | Type | Description |
|---|---|---|
$request |
ServerRequestInterface |
β |
$response |
ResponseInterface |
β |
Returns: ResponseInterface
ProcessFileLock
final class β rafalmasiarek\DashboardKitScheduler\Lock\ProcessFileLock Β· source
Single-file process lock using flock(LOCK_EX|LOCK_NB). Writes JSON metadata (pid + started_at) into the lock file for diagnostics. Registers a shutdown handler and optional PCNTL signal handlers to release the lock on normal exit, SIGTERM, SIGINT and SIGHUP. SIGKILL (kill -9) cannot be handled; the lock file may remain on disk in that case. The advisory lock itself is released by the OS when the process dies.
Depends on: ClockInterface
Package: rafalmasiarek\DashboardKitScheduler
| Property | Type | Visibility | Description |
|---|---|---|---|
$lockPath |
string |
private | β |
$clock |
ClockInterface|null |
private | β |
$fh |
resource|null |
private | β |
$locked |
bool |
private | β |
$handlersInstalled |
bool |
private | β |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | β | β |
acquire() |
public | bool |
Try to acquire the lock (non-blocking). |
release() |
public | void |
Release the lock. |
readMeta() |
public | array<string, mixed>|null |
Read lock metadata written at acquire time (best-effort). |
writeMetaToLockFile() |
private | void |
Write PID and start time into the lock file for diagnostics. |
installHandlers() |
private | void |
Register shutdown and optional PCNTL signal handlers. |
__construct()
ProcessFileLock __construct()
public function __construct(string $lockPath, ?ClockInterface $clock)
| Param | Type | Description |
|---|---|---|
$lockPath |
string |
Absolute path to the lock file. |
$clock |
ClockInterface|null |
Optional clock for lock metadata timestamps. |
acquire()
ProcessFileLock acquire()
public function acquire(): bool
Try to acquire the lock (non-blocking).
Returns: bool β True when the lock was acquired.
readMeta()
ProcessFileLock readMeta()
public function readMeta(): ?array
Read lock metadata written at acquire time (best-effort).
Returns: array<string, mixed>\|null
writeMetaToLockFile()
ProcessFileLock writeMetaToLockFile()
private function writeMetaToLockFile(): void
Write PID and start time into the lock file for diagnostics.
installHandlers()
ProcessFileLock installHandlers()
private function installHandlers(): void
Register shutdown and optional PCNTL signal handlers.
FileLockMiddleware
final class β rafalmasiarek\DashboardKitScheduler\Middleware\FileLockMiddleware Β· source
Per-task file-lock middleware preventing concurrent execution. Lock file path: /.lock Guarantees lock release on normal exit and SIGTERM/SIGINT/SIGHUP when the pcntl extension is available. SIGKILL cannot be handled.
implements TaskMiddlewareInterface
Depends on: ClockInterface
Package: rafalmasiarek\DashboardKitScheduler
| Property | Type | Visibility | Description |
|---|---|---|---|
$locksDir |
string |
private | β |
$clock |
ClockInterface|null |
private | β |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | β | β |
handle() |
public | mixed |
Handle task execution step. |
sanitizeTaskName() |
private | string |
Sanitize task name to a safe filename component. |
__construct()
FileLockMiddleware __construct()
public function __construct(string $locksDir, ?ClockInterface $clock)
| Param | Type | Description |
|---|---|---|
$locksDir |
string |
Directory for lock files (absolute path). |
$clock |
ClockInterface|null |
Optional clock used for lock metadata timestamps. |
| Throws | When |
|---|---|
\RuntimeException |
When $locksDir is empty. |
handle()
FileLockMiddleware handle()
public function handle(string $taskName, array $context, callable $next): mixed
Handle task execution step.
| Param | Type | Description |
|---|---|---|
$taskName |
string |
β |
$context |
array<string, mixed> |
β |
$next |
callable(): mixed |
β |
Returns: mixed
| Throws | When |
|---|---|
TaskLockedException |
When lock cannot be acquired. |
sanitizeTaskName()
FileLockMiddleware sanitizeTaskName()
private function sanitizeTaskName(string $name): string
Sanitize task name to a safe filename component.
| Param | Type | Description |
|---|---|---|
$name |
string |
β |
Returns: string
MonitoringInterface
interface β rafalmasiarek\DashboardKitScheduler\MonitoringInterface Β· source
Monitoring hooks for Scheduler. Implementations may send pings to HealthChecks.io, store metrics, etc. All methods MUST swallow their own exceptions so monitoring never breaks scheduling.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
onTaskRunStart() |
public | void |
Called right before running a task. |
onTaskRunOk() |
public | void |
Called after a successful task run. |
onTaskRunFail() |
public | void |
Called after a failed task run. |
onTaskRunStart()
MonitoringInterface onTaskRunStart()
public function onTaskRunStart(string $taskId, array $context): void
Called right before running a task.
| Param | Type | Description |
|---|---|---|
$taskId |
string |
β |
$context |
array<string, mixed> |
β |
onTaskRunOk()
MonitoringInterface onTaskRunOk()
public function onTaskRunOk(string $taskId, array $record, array $ctx): void
Called after a successful task run.
| Param | Type | Description |
|---|---|---|
$taskId |
string |
β |
$record |
array<string, mixed> |
Full task run record from Scheduler::runTask(). |
$ctx |
array<string, mixed> |
β |
onTaskRunFail()
MonitoringInterface onTaskRunFail()
public function onTaskRunFail(string $taskId, array $record, \Throwable $e, array $ctx): void
Called after a failed task run.
| Param | Type | Description |
|---|---|---|
$taskId |
string |
β |
$record |
array<string, mixed> |
Full task run record from Scheduler::runTask(). |
$e |
\Throwable |
Exception thrown by the task. |
$ctx |
array<string, mixed> |
β |
NoopMonitoring
final class β rafalmasiarek\DashboardKitScheduler\NoopMonitoring Β· source
Default no-op monitoring implementation. Safe to use in all environments where monitoring is not configured.
implements MonitoringInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
onTaskRunStart() |
public | void |
Called right before running a task. |
onTaskRunOk() |
public | void |
Called after a successful task run. |
onTaskRunFail() |
public | void |
Called after a failed task run. |
onTaskRunStart()
NoopMonitoring onTaskRunStart()
public function onTaskRunStart(string $taskId, array $context): void
Called right before running a task.
| Param | Type | Description |
|---|---|---|
$taskId |
string |
β |
$context |
array<string, mixed> |
β |
onTaskRunOk()
NoopMonitoring onTaskRunOk()
public function onTaskRunOk(string $taskId, array $record, array $context): void
Called after a successful task run.
| Param | Type | Description |
|---|---|---|
$taskId |
string |
β |
$record |
array<string, mixed> |
Full task run record from Scheduler::runTask(). |
$context |
array |
β |
onTaskRunFail()
NoopMonitoring onTaskRunFail()
public function onTaskRunFail(string $taskId, array $record, \Throwable $e, array $context): void
Called after a failed task run.
| Param | Type | Description |
|---|---|---|
$taskId |
string |
β |
$record |
array<string, mixed> |
Full task run record from Scheduler::runTask(). |
$e |
\Throwable |
Exception thrown by the task. |
$context |
array |
β |
AbstractOutputPolicy
abstract class β rafalmasiarek\DashboardKitScheduler\Output\AbstractOutputPolicy Β· source
Base implementation for task result output policies. Always includes "final" (the last run's own result); includes "steps" (one entry per run record) only when the "verbose" option is enabled.
implements OutputPolicyInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
buildResult() |
public | array<string, mixed> |
Build the normalized result payload for a task. |
buildSteps() |
protected | array<int, array<string, mixed>> |
Build the "steps" section: one normalized entry per run record. |
extractFinal() |
protected | mixed |
Extract the "final" value from the last run record. |
isEnabled() |
protected | bool |
Read a boolean-ish output option. Accepts native booleans, non-zero ints, and the strings "1"/"true"/"yes"/"on". |
buildStep() |
protected | array<string, mixed> |
Build the normalized payload for a single run record. |
buildResult()
AbstractOutputPolicy buildResult()
public function buildResult(string $taskName, array $runs, array $options): array
Build the normalized result payload for a task.
| Param | Type | Description |
|---|---|---|
$taskName |
string |
Registered task name (e.g. "my_module.my_task"). |
$runs |
array<int, array<string, mixed>> |
Run records in execution order, oldest first. |
$options |
array<string, mixed> |
Output options (e.g. ['verbose' => true]). |
Returns: array<string, mixed>
buildSteps()
AbstractOutputPolicy buildSteps()
protected function buildSteps(array $runs): array
Build the "steps" section: one normalized entry per run record.
| Param | Type | Description |
|---|---|---|
$runs |
array<int, array<string, mixed>> |
β |
Returns: array<int, array<string, mixed>>
extractFinal()
AbstractOutputPolicy extractFinal()
protected function extractFinal(array $runs): mixed
Extract the "final" value from the last run record.
| Param | Type | Description |
|---|---|---|
$runs |
array<int, array<string, mixed>> |
β |
Returns: mixed
isEnabled()
AbstractOutputPolicy isEnabled()
protected function isEnabled(array $options, string $key): bool
Read a boolean-ish output option. Accepts native booleans, non-zero ints, and the strings "1"/"true"/"yes"/"on".
| Param | Type | Description |
|---|---|---|
$options |
array<string, mixed> |
β |
$key |
string |
β |
Returns: bool
buildStep()
AbstractOutputPolicy buildStep()
protected function buildStep(array $run): array
Build the normalized payload for a single run record.
| Param | Type | Description |
|---|---|---|
$run |
array<string, mixed> |
β |
Returns: array<string, mixed>
CronOutputBuilder
final class β rafalmasiarek\DashboardKitScheduler\Output\CronOutputBuilder Β· source
Builds the normalized response payload shared by RunHandler and JobHandler, regardless of whether the task ran directly or through a queue.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
build() |
public static | array<string, mixed> |
Build the normalized payload for a task's run history. |
build()
CronOutputBuilder build()
public static function build(string $taskName, string $mode, array $runs, ?array $queueMeta, array $options): array
Build the normalized payload for a task's run history.
| Param | Type | Description |
|---|---|---|
$taskName |
string |
β |
$mode |
string |
"direct" or "queue". |
$runs |
array<int, array<string, mixed>> |
Run records in execution order, oldest first. |
$queueMeta |
array<string, mixed>|null |
Queue identifiers (id/index/part), null outside a queue. |
$options |
array<string, mixed> |
Output options (e.g. ['verbose' => true]). |
Returns: array<string, mixed>
DefaultOutputPolicy
final class β rafalmasiarek\DashboardKitScheduler\Output\DefaultOutputPolicy Β· source
Default, compact task result policy. Used for any task without a registered task-specific policy.
extends AbstractOutputPolicy
| Method | Visibility | Returns | Summary |
|---|---|---|---|
buildStep() |
protected | array<string, mixed> |
Build the normalized payload for a single run record. |
buildStep()
DefaultOutputPolicy buildStep()
protected function buildStep(array $run): array
Build the normalized payload for a single run record.
| Param | Type | Description |
|---|---|---|
$run |
array<string, mixed> |
β |
Returns: array<string, mixed>
OutputPolicyInterface
interface β rafalmasiarek\DashboardKitScheduler\Output\OutputPolicyInterface Β· source
Builds a normalized result payload from one or more scheduler run records. A policy decides which sections belong in "result" based on output options (currently just "verbose", read from the request's passthrough query).
| Method | Visibility | Returns | Summary |
|---|---|---|---|
buildResult() |
public | array<string, mixed> |
Build the normalized result payload for a task. |
buildResult()
OutputPolicyInterface buildResult()
public function buildResult(string $taskName, array $runs, array $options): array
Build the normalized result payload for a task.
| Param | Type | Description |
|---|---|---|
$taskName |
string |
Registered task name (e.g. "my_module.my_task"). |
$runs |
array<int, array<string, mixed>> |
Run records in execution order, oldest first. |
$options |
array<string, mixed> |
Output options (e.g. ['verbose' => true]). |
Returns: array<string, mixed>
OutputPolicyResolver
final class β rafalmasiarek\DashboardKitScheduler\Output\OutputPolicyResolver Β· source
Resolves the output policy for a given task name. Falls back to DefaultOutputPolicy for any task without a registered task-specific policy.
| Property | Type | Visibility | Description |
|---|---|---|---|
$policies |
array<string, class-string<OutputPolicyInterface>> |
private static | β |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
register() |
public static | void |
Register a task-specific output policy class. |
for() |
public static | OutputPolicyInterface |
Resolve the output policy instance for a task. |
register()
OutputPolicyResolver register()
public static function register(string $taskName, string $policyClass): void
Register a task-specific output policy class.
| Param | Type | Description |
|---|---|---|
$taskName |
string |
Full task name (e.g. "my_module.my_task"). |
$policyClass |
class-string<OutputPolicyInterface> |
β |
for()
OutputPolicyResolver for()
public static function for(string $taskName): OutputPolicyInterface
Resolve the output policy instance for a task.
| Param | Type | Description |
|---|---|---|
$taskName |
string |
β |
Returns: OutputPolicyInterface
PdoStateStore
final class β rafalmasiarek\DashboardKitScheduler\PdoStateStore Β· source
PDO-based implementation of SchedulerStateStore. Works with SQLite, MySQL and PostgreSQL. Table schema is created automatically on construction. Logs schema.created to the provided logger the first time the table is created.
implements SchedulerStateStore
Depends on: PDO, LoggerInterface
| Property | Type | Visibility | Description |
|---|---|---|---|
$pdo |
PDO |
private | β |
$table |
string |
private | β |
$logger |
LoggerInterface|null |
private | β |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | β | β |
read() |
public | string|null |
Read a value by key. |
write() |
public | void |
Write a value by key. |
delete() |
public | void |
Delete a value by key. |
initSchema() |
public | void |
Create the state table if it does not exist. Logs schema.created at info level the first time the table is actually created. |
tableExists() |
private | bool |
Check whether the state table exists by attempting a lightweight query. |
__construct()
PdoStateStore __construct()
public function __construct(PDO $pdo, ?string $table, ?LoggerInterface $logger)
| Param | Type | Description |
|---|---|---|
$pdo |
PDO |
Ready PDO connection. |
$table |
string|null |
Table name (default: "scheduler_state"). |
$logger |
LoggerInterface|null |
Optional logger for schema creation events. |
read()
PdoStateStore read()
public function read(string $key): ?string
Read a value by key.
| Param | Type | Description |
|---|---|---|
$key |
string |
β |
Returns: string\|null
write()
PdoStateStore write()
public function write(string $key, string $value): void
Write a value by key.
| Param | Type | Description |
|---|---|---|
$key |
string |
β |
$value |
string |
β |
delete()
PdoStateStore delete()
public function delete(string $key): void
Delete a value by key.
| Param | Type | Description |
|---|---|---|
$key |
string |
β |
initSchema()
PdoStateStore initSchema()
public function initSchema(): void
Create the state table if it does not exist. Logs schema.created at info level the first time the table is actually created.
tableExists()
PdoStateStore tableExists()
private function tableExists(): bool
Check whether the state table exists by attempting a lightweight query.
Returns: bool
QueuePayload
final class β rafalmasiarek\DashboardKitScheduler\QueuePayload Β· source
Per-queue key-value storage persisted inside the queue state JSON file. In direct mode (no queue_state_path), it falls back to in-memory storage and never throws. In queue mode, coordinates writes via a ".lock" file using the same convention as the queue runner.
| Property | Type | Visibility | Description |
|---|---|---|---|
$queueStatePath |
string|null |
private | When null the payload is in-memory only (no persistence). |
$memory |
array<string, mixed> |
private | β |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | β | β |
fromContext() |
public static | self |
Create payload accessor from scheduler context array. Accepts common context shapes: - flat: ['queue_state_path' => '...'] - nested: ['context' => ['queue_state_path' => '...']] - nested: ['data' => ['queue_state_path' => '...']] Returns in-memory instance when path is missing. |
isPersistent() |
public | bool |
Whether the payload is persisted to the queue file. |
get() |
public | mixed |
Get a value by key. |
put() |
public | void |
Store a value by key. |
delete() |
public | void |
Remove a value by key. |
clear() |
public | void |
Clear all payload values. |
withLock() |
private | T |
Execute callback while holding an exclusive lock on the queue file. |
readStateUnlocked() |
private | array<string, mixed> |
Read full queue state JSON without locking (caller must hold lock). |
writeStateUnlocked() |
private | void |
Persist full queue state JSON atomically without locking (caller must hold lock). |
readPayload() |
private | array<string, mixed> |
Extract the payload sub-array from a queue state array. |
__construct()
QueuePayload __construct()
public function __construct(?string $queueStatePath)
| Param | Type | Description |
|---|---|---|
$queueStatePath |
string|null |
Absolute path to the queue JSON file, or null for in-memory. |
fromContext()
QueuePayload fromContext()
public static function fromContext(array $context): self
Create payload accessor from scheduler context array. Accepts common context shapes: - flat: ['queue_state_path' => '...'] - nested: ['context' => ['queue_state_path' => '...']] - nested: ['data' => ['queue_state_path' => '...']] Returns in-memory instance when path is missing.
| Param | Type | Description |
|---|---|---|
$context |
array<string, mixed> |
β |
Returns: self
isPersistent()
QueuePayload isPersistent()
public function isPersistent(): bool
Whether the payload is persisted to the queue file.
Returns: bool
get()
QueuePayload get()
public function get(string $key, mixed $default): mixed
Get a value by key.
| Param | Type | Description |
|---|---|---|
$key |
string |
β |
$default |
mixed |
β |
Returns: mixed
put()
QueuePayload put()
public function put(string $key, mixed $value): void
Store a value by key.
| Param | Type | Description |
|---|---|---|
$key |
string |
β |
$value |
mixed |
β |
delete()
QueuePayload delete()
public function delete(string $key): void
Remove a value by key.
| Param | Type | Description |
|---|---|---|
$key |
string |
β |
withLock()
QueuePayload withLock()
private function withLock(callable $fn):
Execute callback while holding an exclusive lock on the queue file.
| Param | Type | Description |
|---|---|---|
$fn |
callable(): T |
β |
Returns: T
readStateUnlocked()
QueuePayload readStateUnlocked()
private function readStateUnlocked(): array
Read full queue state JSON without locking (caller must hold lock).
Returns: array<string, mixed>
writeStateUnlocked()
QueuePayload writeStateUnlocked()
private function writeStateUnlocked(array $state): void
Persist full queue state JSON atomically without locking (caller must hold lock).
| Param | Type | Description |
|---|---|---|
$state |
array<string, mixed> |
β |
readPayload()
QueuePayload readPayload()
private function readPayload(array $state): array
Extract the payload sub-array from a queue state array.
| Param | Type | Description |
|---|---|---|
$state |
array<string, mixed> |
β |
Returns: array<string, mixed>
Scheduler
class β rafalmasiarek\DashboardKitScheduler\Scheduler Β· source
In-process cron-expression task scheduler. - Stores last-run timestamps via a pluggable SchedulerStateStore. - Prevents duplicate executions within the same minute. - Supports catch-up of missed runs via dragonmantank/cron-expression. - Tasks can carry a per-task middleware pipeline (e.g. file locks). - Tasks are indexed by name; registration is idempotent within a request.
Depends on: SchedulerStateStore, MonitoringInterface, ClockInterface
| Property | Type | Visibility | Description |
|---|---|---|---|
$tasks |
array<string, array{expression: string, callback: callable, middlewares: array<int, TaskMiddlewareInterface>, cron: ?CronExpression, opt: array<string, mixed>, allow_concurrent: bool}> |
private | Registered tasks indexed by task name. |
$defaultNoOverlap |
bool |
private | When true, tasks are non-overlapping by default. |
$locksDir |
string |
private | Directory for per-task lock files. |
$store |
SchedulerStateStore |
private | Pluggable state store for last-run timestamps. |
$monitoring |
MonitoringInterface |
private | Optional monitoring implementation. |
$clock |
ClockInterface |
private | Shared time source. |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | β | Create a new Scheduler instance. When $store is null, a FileStateStore is created using $runtimeDir (or the SCHEDULER_STATE_DIR environment variable, falling back to "/../storage"). |
state() |
public | SchedulerStateStore |
Expose the shared state store. |
payloadFrom() |
public | QueuePayload |
Build a QueuePayload accessor from a context array. |
add() |
public | void |
Register a task. A FileLockMiddleware is prepended automatically when $defaultNoOverlap is true and $allowConcurrent is false. |
addWithMiddlewares() |
public | void |
Register a task with an explicit middleware list. When $defaultNoOverlap is true and $allowConcurrent is false, a FileLockMiddleware is prepended before the provided list. |
listDueTasks() |
public | string[] |
List names of tasks that are due at the given time. |
describeTasks() |
public | array<string, array{name: string, expression: string, last_run_ts: int|null, last_run_at: string|null, is_due: bool}> |
Describe all registered tasks with last-run state and due flag. |
runDueTasksDetailed() |
public | array<int, array{name: string, started_at: string, finished_at: string, duration_ms: int, status: string, result: mixed, error: array{type: string, message: string}|null}> |
Run all due tasks and return structured records. |
runDueTasks() |
public | string[] |
Run all due tasks and return names of successfully executed tasks. |
runTask() |
public | array<string, mixed> |
Execute a single task run. When $force is false the task runs only if due (or allowed step execution via context). last_started_at is stamped early to reduce minute-later re-trigger attempts. |
isDueOrMissed() |
private | bool |
Decide whether a task is due or has a missed run at $now. Concurrency policy: - allow_concurrent: schedule solely from last_run. - non-overlapping: use last_started_at as in-progress anchor when fresh. Stale run detection: started_at older than max_runtime_sec (default 3600) is ignored. |
lastStartedAt() |
private | int|null |
Read the last_started_at timestamp for a task. |
stampStartedAt() |
private | int |
Stamp last_started_at to mark task as in-progress. |
clearStartedAt() |
private | void |
Clear last_started_at after task completion. Uses "0" sentinel for stores that do not support key deletion. |
lastRun() |
private | int|null |
Read last_run timestamp for a task. |
markAsRun() |
private | int |
Persist last_run timestamp after successful execution. |
buildCronExpression() |
private | CronExpression |
Build and validate a CronExpression. |
getCronForTask() |
private | CronExpression |
Return the cached CronExpression for a registered task. |
executeWithMiddlewares() |
private | mixed |
Execute task callback through the registered middleware pipeline. |
invokeCallbackCompat() |
private | mixed |
Invoke callback with backward-compatible signature support. Supports callable(TaskContext) and callable(). |
buildRuntimeOptions() |
private | array<string, mixed> |
Build final runtime options from base config and request context. Rules: - Start from task base options (registered with add()). - Apply overrides from context (GET params / queue passthrough). - Context wins when value !== null and !== ''. - Internal scheduler/queue keys are stripped. - Scalars are coerced to base option types (bool/int/float). |
coerceOverridesByBaseTypes() |
private | array<string, mixed> |
Coerce override scalar values to match the types declared in $base. |
toBool() |
private | bool |
Parse a boolean from common GET/ENV forms. |
__construct()
Scheduler __construct()
public function __construct(?SchedulerStateStore $store, ?string $runtimeDir, mixed $timezone, ?MonitoringInterface $monitoring, ?ClockInterface $clock, ?string $locksDir, bool $defaultNoOverlap)
Create a new Scheduler instance. When $store is null, a FileStateStore is created using $runtimeDir (or the SCHEDULER_STATE_DIR environment variable, falling back to "/../storage").
| Param | Type | Description |
|---|---|---|
$store |
SchedulerStateStore|null |
Pluggable state store. |
$runtimeDir |
string|null |
Path for the default FileStateStore. |
$timezone |
mixed |
Deprecated, ignored β pass $clock instead. |
$monitoring |
MonitoringInterface|null |
Monitoring implementation (default: NoopMonitoring). |
$clock |
ClockInterface|null |
Shared time source. |
$locksDir |
string|null |
Directory for lock files. |
$defaultNoOverlap |
bool |
Whether tasks are non-overlapping by default. |
state()
Scheduler state()
public function state(): SchedulerStateStore
Expose the shared state store.
Returns: SchedulerStateStore
payloadFrom()
Scheduler payloadFrom()
public function payloadFrom(array $ctx): QueuePayload
Build a QueuePayload accessor from a context array.
| Param | Type | Description |
|---|---|---|
$ctx |
array<string, mixed> |
β |
Returns: QueuePayload
add()
Scheduler add()
public function add(string $expression, callable $callback, string $name, array $optBase, bool $allowConcurrent): void
Register a task. A FileLockMiddleware is prepended automatically when $defaultNoOverlap is true and $allowConcurrent is false.
| Param | Type | Description |
|---|---|---|
$expression |
string |
Cron expression (e.g. "* * * * *"). |
$callback |
callable |
Task callback; receives TaskContext when it accepts >= 1 parameter. |
$name |
string |
Unique task name. |
$optBase |
array<string, mixed> |
Base options merged with runtime context at execution. |
$allowConcurrent |
bool |
When true, disables the default no-overlap lock. |
addWithMiddlewares()
Scheduler addWithMiddlewares()
public function addWithMiddlewares(string $expression, callable $callback, string $name, array $middlewares, array $optBase, bool $allowConcurrent): void
Register a task with an explicit middleware list. When $defaultNoOverlap is true and $allowConcurrent is false, a FileLockMiddleware is prepended before the provided list.
| Param | Type | Description |
|---|---|---|
$expression |
string |
β |
$callback |
callable |
β |
$name |
string |
β |
$middlewares |
array<int, TaskMiddlewareInterface> |
β |
$optBase |
array<string, mixed> |
β |
$allowConcurrent |
bool |
β |
listDueTasks()
Scheduler listDueTasks()
public function listDueTasks(?\DateTimeInterface $now): array
List names of tasks that are due at the given time.
| Param | Type | Description |
|---|---|---|
$now |
\DateTimeInterface|null |
β |
Returns: string[]
describeTasks()
Scheduler describeTasks()
public function describeTasks(?\DateTimeInterface $now): array
Describe all registered tasks with last-run state and due flag.
| Param | Type | Description |
|---|---|---|
$now |
\DateTimeInterface|null |
β |
Returns: array<string, array{name: string, expression: string, last_run_ts: int\|null, last_run_at: string\|null, is_due: bool}>
runDueTasksDetailed()
Scheduler runDueTasksDetailed()
public function runDueTasksDetailed(): array
Run all due tasks and return structured records.
Returns: array<int, array{name: string, started_at: string, finished_at: string, duration_ms: int, status: string, result: mixed, error: array{type: string, message: string}\|null}>
runDueTasks()
Scheduler runDueTasks()
public function runDueTasks(): array
Run all due tasks and return names of successfully executed tasks.
Returns: string[]
runTask()
Scheduler runTask()
public function runTask(string $name, bool $force, ?array $context): array
Execute a single task run. When $force is false the task runs only if due (or allowed step execution via context). last_started_at is stamped early to reduce minute-later re-trigger attempts.
| Param | Type | Description |
|---|---|---|
$name |
string |
β |
$force |
bool |
When true, bypasses due-check and does not persist state. |
$context |
array<string, mixed>|null |
Runtime context (queue params, passthrough query params, etc.). |
Returns: array<string, mixed>
isDueOrMissed()
Scheduler isDueOrMissed()
private function isDueOrMissed(string $name, \DateTimeInterface $now): bool
Decide whether a task is due or has a missed run at $now. Concurrency policy: - allow_concurrent: schedule solely from last_run. - non-overlapping: use last_started_at as in-progress anchor when fresh. Stale run detection: started_at older than max_runtime_sec (default 3600) is ignored.
| Param | Type | Description |
|---|---|---|
$name |
string |
β |
$now |
\DateTimeInterface |
β |
Returns: bool
lastStartedAt()
Scheduler lastStartedAt()
private function lastStartedAt(string $name): ?int
Read the last_started_at timestamp for a task.
| Param | Type | Description |
|---|---|---|
$name |
string |
β |
Returns: int\|null
stampStartedAt()
Scheduler stampStartedAt()
private function stampStartedAt(string $name, ?\DateTimeInterface $now): int
Stamp last_started_at to mark task as in-progress.
| Param | Type | Description |
|---|---|---|
$name |
string |
β |
$now |
\DateTimeInterface|null |
β |
Returns: int
clearStartedAt()
Scheduler clearStartedAt()
private function clearStartedAt(string $name): void
Clear last_started_at after task completion. Uses "0" sentinel for stores that do not support key deletion.
| Param | Type | Description |
|---|---|---|
$name |
string |
β |
lastRun()
Scheduler lastRun()
private function lastRun(string $name): ?int
Read last_run timestamp for a task.
| Param | Type | Description |
|---|---|---|
$name |
string |
β |
Returns: int\|null
markAsRun()
Scheduler markAsRun()
private function markAsRun(string $name, ?CronExpression $expr, ?\DateTimeInterface $now): int
Persist last_run timestamp after successful execution.
| Param | Type | Description |
|---|---|---|
$name |
string |
β |
$expr |
CronExpression|null |
Unused; kept for signature compatibility. |
$now |
\DateTimeInterface|null |
β |
Returns: int
buildCronExpression()
Scheduler buildCronExpression()
private function buildCronExpression(string $expression, string $taskName): CronExpression
Build and validate a CronExpression.
| Param | Type | Description |
|---|---|---|
$expression |
string |
β |
$taskName |
string |
β |
Returns: CronExpression
| Throws | When |
|---|---|
\InvalidArgumentException |
When the expression is invalid. |
getCronForTask()
Scheduler getCronForTask()
private function getCronForTask(string $name): CronExpression
Return the cached CronExpression for a registered task.
| Param | Type | Description |
|---|---|---|
$name |
string |
β |
Returns: CronExpression
executeWithMiddlewares()
Scheduler executeWithMiddlewares()
private function executeWithMiddlewares(string $name, callable $cb, array $ctx, TaskContext $taskContext): mixed
Execute task callback through the registered middleware pipeline.
| Param | Type | Description |
|---|---|---|
$name |
string |
β |
$cb |
callable |
β |
$ctx |
array<string, mixed> |
β |
$taskContext |
TaskContext |
β |
Returns: mixed
invokeCallbackCompat()
Scheduler invokeCallbackCompat()
private function invokeCallbackCompat(callable $cb, TaskContext $context): mixed
Invoke callback with backward-compatible signature support. Supports callable(TaskContext) and callable().
| Param | Type | Description |
|---|---|---|
$cb |
callable |
β |
$context |
TaskContext |
β |
Returns: mixed
buildRuntimeOptions()
Scheduler buildRuntimeOptions()
private function buildRuntimeOptions(array $base, array $ctx): array
Build final runtime options from base config and request context. Rules: - Start from task base options (registered with add()). - Apply overrides from context (GET params / queue passthrough). - Context wins when value !== null and !== ''. - Internal scheduler/queue keys are stripped. - Scalars are coerced to base option types (bool/int/float).
| Param | Type | Description |
|---|---|---|
$base |
array<string, mixed> |
β |
$ctx |
array<string, mixed> |
β |
Returns: array<string, mixed>
coerceOverridesByBaseTypes()
Scheduler coerceOverridesByBaseTypes()
private function coerceOverridesByBaseTypes(array $base, array $overrides): array
Coerce override scalar values to match the types declared in $base.
| Param | Type | Description |
|---|---|---|
$base |
array<string, mixed> |
β |
$overrides |
array<string, mixed> |
β |
Returns: array<string, mixed>
toBool()
Scheduler toBool()
private function toBool(mixed $v): bool
Parse a boolean from common GET/ENV forms.
| Param | Type | Description |
|---|---|---|
$v |
mixed |
β |
Returns: bool
SchedulerAddon
final class β rafalmasiarek\DashboardKitScheduler\SchedulerAddon Β· source
Wires the scheduler engine into a Dashboard application.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
register() |
public static | void |
Register the scheduler addon. |
loadSystemTasks() |
private static | void |
Register system-level tasks defined in app.config['cron']. Each task's global ID is: system. Config format: 'cron' => [ 'my-task' => [ 'cron' => '0 3 * * *', 'handler' => static function (): void { ... }, 'enabled' => true, // optional, default true ], ], |
loadTasks() |
private static | void |
Discover and register tasks from all modules that define a 'schedule' key. Each task's global ID is: . |
buildTaskRegistry() |
private static | TaskRegistry |
Build the built-in task factory registry. |
cleanupQueueFiles() |
private static | void |
Remove queue JSON files older than 24 hours from the queue directory. |
register()
SchedulerAddon register()
public static function register(App $app, ContainerInterface $container, array $config): void
Register the scheduler addon.
| Param | Type | Description |
|---|---|---|
$app |
App |
β |
$container |
ContainerInterface |
β |
$config |
array<string, mixed> |
Optional configuration overrides. |
loadSystemTasks()
SchedulerAddon loadSystemTasks()
private static function loadSystemTasks(Scheduler $scheduler, array $appConfig, ContainerInterface $container, ClockInterface $clock, ?LoggerInterface $logger): void
Register system-level tasks defined in app.config['cron']. Each task's global ID is: system. Config format: 'cron' => [ 'my-task' => [ 'cron' => '0 3 * * *', 'handler' => static function (): void { ... }, 'enabled' => true, // optional, default true ], ],
| Param | Type | Description |
|---|---|---|
$scheduler |
Scheduler |
β |
$appConfig |
array<string, mixed> |
β |
$container |
ContainerInterface |
β |
$clock |
ClockInterface |
β |
$logger |
LoggerInterface|null |
β |
loadTasks()
SchedulerAddon loadTasks()
private static function loadTasks(Scheduler $scheduler, ModuleRegistry $registry, ContainerInterface $container, ClockInterface $clock, ?LoggerInterface $logger): void
Discover and register tasks from all modules that define a 'schedule' key. Each task's global ID is: .
| Param | Type | Description |
|---|---|---|
$scheduler |
Scheduler |
β |
$registry |
ModuleRegistry |
β |
$container |
ContainerInterface |
β |
$clock |
ClockInterface |
β |
$logger |
LoggerInterface|null |
Optional logger for config errors and load summary. |
buildTaskRegistry()
SchedulerAddon buildTaskRegistry()
private static function buildTaskRegistry(): TaskRegistry
Build the built-in task factory registry.
Returns: TaskRegistry
cleanupQueueFiles()
SchedulerAddon cleanupQueueFiles()
private static function cleanupQueueFiles(string $dir): void
Remove queue JSON files older than 24 hours from the queue directory.
| Param | Type | Description |
|---|---|---|
$dir |
string |
β |
SchedulerStateStore
interface β rafalmasiarek\DashboardKitScheduler\SchedulerStateStore Β· source
Interface for storing scheduler state (last run timestamps, etc.).
| Method | Visibility | Returns | Summary |
|---|---|---|---|
read() |
public | string|null |
Read a value by key. |
write() |
public | void |
Write a value by key. |
delete() |
public | void |
Delete a value by key. |
read()
SchedulerStateStore read()
public function read(string $key): ?string
Read a value by key.
| Param | Type | Description |
|---|---|---|
$key |
string |
β |
Returns: string\|null
write()
SchedulerStateStore write()
public function write(string $key, string $value): void
Write a value by key.
| Param | Type | Description |
|---|---|---|
$key |
string |
β |
$value |
string |
β |
delete()
SchedulerStateStore delete()
public function delete(string $key): void
Delete a value by key.
| Param | Type | Description |
|---|---|---|
$key |
string |
β |
SchedulerSchemaProvider
final class β rafalmasiarek\DashboardKitScheduler\Schema\SchedulerSchemaProvider Β· source
Provides the scheduler state table schema to AuthKit's createSchema() mechanism. Usage in SchedulerAddon::register(): $auth->createSchema(new SchedulerSchemaProvider()); The SQL statements are idempotent (CREATE TABLE IF NOT EXISTS).
implements SchemaProviderInterface
Package: rafalmasiarek\DashboardKitScheduler
| Method | Visibility | Returns | Summary |
|---|---|---|---|
additionalSchema() |
public | string[] |
Return idempotent SQL statements for the given DB driver. |
additionalSchema()
SchedulerSchemaProvider additionalSchema()
public function additionalSchema(string $driver): array
Return idempotent SQL statements for the given DB driver.
| Param | Type | Description |
|---|---|---|
$driver |
string |
PDO driver name ("mysql", "sqlite", "pgsql"). |
Returns: string[]
SystemLogMonitoring
final class β rafalmasiarek\DashboardKitScheduler\SystemLogMonitoring Β· source
Logs task execution lifecycle events to a PSR-3 logger (typically logger.system). Auto-wired by SchedulerAddon when logger.system is available in the DI container and no explicit MonitoringInterface binding exists. Emitted events: task.start β info β emitted right before a task begins execution task.ok β info β emitted after successful completion task.locked β warning β emitted when concurrent execution was blocked by FileLockMiddleware task.fail β error β emitted when the task threw an unhandled exception
implements MonitoringInterface
Depends on: LoggerInterface
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | β | β |
onTaskRunStart() |
public | void |
Called right before running a task. |
onTaskRunOk() |
public | void |
Called after a successful task run. |
onTaskRunFail() |
public | void |
Called after a failed task run. |
__construct()
SystemLogMonitoring __construct()
public function __construct(LoggerInterface $logger)
| Param | Type | Description |
|---|---|---|
$logger |
LoggerInterface |
Logger to write lifecycle events to. |
onTaskRunStart()
SystemLogMonitoring onTaskRunStart()
public function onTaskRunStart(string $taskId, array $context): void
Called right before running a task.
| Param | Type | Description |
|---|---|---|
$taskId |
string |
β |
$context |
array<string, mixed> |
β |
onTaskRunOk()
SystemLogMonitoring onTaskRunOk()
public function onTaskRunOk(string $taskId, array $record, array $ctx): void
Called after a successful task run.
| Param | Type | Description |
|---|---|---|
$taskId |
string |
β |
$record |
array<string, mixed> |
Full task run record from Scheduler::runTask(). |
$ctx |
array<string, mixed> |
β |
onTaskRunFail()
SystemLogMonitoring onTaskRunFail()
public function onTaskRunFail(string $taskId, array $record, \Throwable $e, array $ctx): void
Called after a failed task run.
| Param | Type | Description |
|---|---|---|
$taskId |
string |
β |
$record |
array<string, mixed> |
Full task run record from Scheduler::runTask(). |
$e |
\Throwable |
Exception thrown by the task. |
$ctx |
array<string, mixed> |
β |
CallableTaskFactory
final class β rafalmasiarek\DashboardKitScheduler\Task\Builtin\CallableTaskFactory Β· source
Action: callable Invokes an arbitrary PHP callable (closure, "Class@method", "Class::method"). Target is read from $options['handler'] at runtime.
implements TaskFactoryInterface
Package: rafalmasiarek\DashboardKitScheduler
| Method | Visibility | Returns | Summary |
|---|---|---|---|
build() |
public | callable |
Build a task callback. |
resolveCallable() |
private static | callable|null |
Resolve a callable from a mixed target value. Supports: Closure, "Class@method", "Class::method", or any PHP callable. |
invokeCallableCompat() |
private | mixed |
Invoke callable preserving the Scheduler compatibility contract. Passes TaskContext + ContainerInterface when the callable accepts >= 2 parameters, TaskContext only when it accepts 1, or no args when it accepts 0. |
build()
CallableTaskFactory build()
public function build(string $taskId, ContainerInterface $container, ClockInterface $clock, array $options): callable
Build a task callback.
| Param | Type | Description |
|---|---|---|
$taskId |
string |
Task identifier. |
$container |
ContainerInterface |
PSR-11 container for service resolution. |
$clock |
ClockInterface |
Shared clock for task runtime. |
$options |
array<string, mixed> |
Task options from the module schedule definition. |
Returns: callable
resolveCallable()
CallableTaskFactory resolveCallable()
private static function resolveCallable(mixed $target): ?callable
Resolve a callable from a mixed target value. Supports: Closure, "Class@method", "Class::method", or any PHP callable.
| Param | Type | Description |
|---|---|---|
$target |
mixed |
β |
Returns: callable\|null
invokeCallableCompat()
CallableTaskFactory invokeCallableCompat()
private function invokeCallableCompat(callable $cb, TaskContext $context, ContainerInterface $container): mixed
Invoke callable preserving the Scheduler compatibility contract. Passes TaskContext + ContainerInterface when the callable accepts >= 2 parameters, TaskContext only when it accepts 1, or no args when it accepts 0.
| Param | Type | Description |
|---|---|---|
$cb |
callable |
β |
$context |
TaskContext |
β |
$container |
ContainerInterface |
β |
Returns: mixed
TaskFactoryInterface
interface β rafalmasiarek\DashboardKitScheduler\Task\TaskFactoryInterface Β· source
Builds a task callback from a task definition. The returned callable is compatible with Scheduler callback invocation rules: - It may accept a single TaskContext parameter. - It may accept no parameters (legacy compatibility). Factories must not concern themselves with scheduler internals (locking, due logic, state). Their responsibility is translating config/options into executable task logic.
Package: rafalmasiarek\DashboardKitScheduler
| Method | Visibility | Returns | Summary |
|---|---|---|---|
build() |
public | callable |
Build a task callback. |
build()
TaskFactoryInterface build()
public function build(string $taskId, ContainerInterface $container, ClockInterface $clock, array $options): callable
Build a task callback.
| Param | Type | Description |
|---|---|---|
$taskId |
string |
Task identifier. |
$container |
ContainerInterface |
PSR-11 container for service resolution. |
$clock |
ClockInterface |
Shared clock for task runtime. |
$options |
array<string, mixed> |
Task options from the module schedule definition. |
Returns: callable
TaskRegistry
final class β rafalmasiarek\DashboardKitScheduler\Task\TaskRegistry Β· source
Action-to-factory registry. Maps action name strings (from module schedule definitions) to TaskFactoryInterface implementations. Used by SchedulerAddon to resolve the right factory per task.
Package: rafalmasiarek\DashboardKitScheduler
| Property | Type | Visibility | Description |
|---|---|---|---|
$factories |
array<string, TaskFactoryInterface> |
private | β |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
register() |
public | void |
Register a factory for an action name. |
get() |
public | TaskFactoryInterface|null |
Resolve the factory for an action name. |
register()
TaskRegistry register()
public function register(string $action, TaskFactoryInterface $factory): void
Register a factory for an action name.
| Param | Type | Description |
|---|---|---|
$action |
string |
β |
$factory |
TaskFactoryInterface |
β |
get()
TaskRegistry get()
public function get(string $action): ?TaskFactoryInterface
Resolve the factory for an action name.
| Param | Type | Description |
|---|---|---|
$action |
string |
β |
Returns: TaskFactoryInterface\|null
TaskContext
final class β rafalmasiarek\DashboardKitScheduler\TaskContext Β· source
Object wrapper passed into task callbacks. Provides named, typed access to task runtime data: - $context->taskName β registered task name - $context->data β raw context array from the queue/HTTP request - $context->opt β final merged options (single source of truth) - $context->state β scheduler state store (last_run, etc.) - $context->payload β per-queue payload (persisted when queue_state_path present) - $context->clock β shared clock instance
Depends on: SchedulerStateStore, QueuePayload, ClockInterface
| Property | Type | Visibility | Description |
|---|---|---|---|
$taskName |
string |
public | β |
$data |
array<string, mixed> |
public | β |
$opt |
array<string, mixed> |
public | Final merged options for this run (config base + context overrides). |
$state |
SchedulerStateStore |
public | β |
$payload |
QueuePayload |
public | β |
$clock |
ClockInterface |
public | β |
| Method | Visibility | Returns | Summary |
|---|---|---|---|
__construct() |
public | β | β |
get() |
public | mixed |
Convenience getter for raw context keys. |
mergeOpt() |
public static | array<string, mixed> |
Merge options with "context wins" semantics. Null and empty-string values do not override base. |
__construct()
TaskContext __construct()
public function __construct(string $taskName, array $data, array $opt, SchedulerStateStore $state, QueuePayload $payload, ClockInterface $clock)
| Param | Type | Description |
|---|---|---|
$taskName |
string |
β |
$data |
array<string, mixed> |
β |
$opt |
array<string, mixed> |
β |
$state |
SchedulerStateStore |
β |
$payload |
QueuePayload |
β |
$clock |
ClockInterface |
β |
get()
TaskContext get()
public function get(string $key, mixed $default): mixed
Convenience getter for raw context keys.
| Param | Type | Description |
|---|---|---|
$key |
string |
β |
$default |
mixed |
β |
Returns: mixed
mergeOpt()
TaskContext mergeOpt()
public static function mergeOpt(array $base, array $ctx): array
Merge options with "context wins" semantics. Null and empty-string values do not override base.
| Param | Type | Description |
|---|---|---|
$base |
array<string, mixed> |
β |
$ctx |
array<string, mixed> |
β |
Returns: array<string, mixed>
TaskMiddlewareInterface
interface β rafalmasiarek\DashboardKitScheduler\TaskMiddlewareInterface Β· source
Middleware pipeline for task execution. Implementations must call $next() to continue execution.
| Method | Visibility | Returns | Summary |
|---|---|---|---|
handle() |
public | mixed |
Handle task execution step. |