Search by

adachsoft / scheduler

Arkadiusz Adach

A PHP job scheduler with recurring schedules, persistent state, run history, health status, and timeout-enforced child-process execution.

Package info

gitlab.com/a.adach/scheduler

Issues

pkg:composer/adachsoft/scheduler

Statistics

Installs: 6

Dependents: 1

Suggesters: 0

Stars: 0

v0.1.0 2026-11-19 16:29 UTC

This package is auto-updated.

Last update: 2026-11-19 15:29:53 UTC


README

adachsoft/scheduler provides recurring job scheduling, execution, persistence, run history, and health reporting for PHP 8.3+ applications. It supports interval and daily schedules, file-backed or in-memory state, job locks, and child-process execution with hard timeouts. Explicit scheduler ticks work with cron, long-running workers, or framework integrations.

Installation

composer require adachsoft/scheduler

Create job definitions and an executor, then use SchedulerFactory to assemble file-backed or in-memory services. Call tick() from a cron task or run SchedulerWorker in a long-lived process. See the usage example for setup details.

Requirements

  • PHP 8.3 or newer.
  • The child-process executor requires the process-control capabilities documented by adachsoft/command-executor-lib.

Usage

Define a JobDefinitionDto for each job and provide a JobDefinitionProviderInterface implementation. Create an executor and pass both to SchedulerFactory::createFileBased() or SchedulerFactory::createInMemory(). Call tick() from cron or run SchedulerWorker for continuous scheduling. A complete worker example is available in docs/examples/file-backed-worker.md.

Schedules and policies

  • IntervalSchedule runs a job at a fixed interval in seconds.
  • DailyAtSchedule runs a job at a configured local time; its default time zone is UTC.
  • JobPolicyDto configures the maximum run time (timeoutSeconds), process termination grace (killGraceSeconds), optional lock lease (lockTtlSeconds), retry delay (retryDelaySeconds), overdue grace (overdueGraceSeconds), failure threshold (failureThreshold), and history retention (historyRetentionDays).

Runtime semantics

  • A scheduler tick executes a due job at most once. Missed occurrences are coalesced; the next scheduled time is calculated from the current time rather than replaying every missed interval.
  • A failed execution can be retried after retryDelaySeconds. The earlier of the retry time and the next scheduled occurrence is selected.
  • A job lock is held for the configured lease. File-based services use file locks; in-memory services use process-local locks.
  • If a worker disappears while a run is active, the scheduler marks it failed after its deadline and kill-grace period once the lock is no longer held.
  • Run history is retained according to historyRetentionDays. Expired records are pruned no more than once per job every 24 hours.

Job execution

ProcessJobExecutor uses adachsoft/command-executor-lib to run a job in a child PHP process and enforce the job timeout. On timeout, the command executor sends SIGTERM to the entire process group and sends SIGKILL after the configured killGraceSeconds if processes remain, terminating descendants as well. It appends the job identifier to the configured command prefix and writes a JSON object containing the normalized run context to the child's standard input:

{"context": {"job_id": "pricing.sync", "run_id": "..."}}

The child may write other output, but its final result is the last standard-output line beginning with @@SCHEDULER_RESULT@@. A successful result has this shape:

@@SCHEDULER_RESULT@@{"status":"succeeded","result":{"message":"Synchronized","warnings":[],"metadata":{}}}

A failed result has this shape:

@@SCHEDULER_RESULT@@{"status":"failed","error_message":"Synchronization failed","error_class":"RuntimeException"}

InProcessJobExecutor runs the job in the worker process and does not provide a hard timeout. Choose it only when the job's runtime is controlled by the application.

Health status

JobHealthEvaluator applies these rules in order:

  1. Missing state is PENDING.
  2. Reaching failureThreshold consecutive failures is FAILING.
  3. An active run is RUNNING.
  4. A next-run time strictly later than its overdue-grace boundary is OVERDUE.
  5. A job with no completed run is PENDING.
  6. Otherwise the job is OK.

JobStatusProviderInterface exposes individual and ordered status snapshots for health endpoints and monitoring integrations.

Worker and factory

SchedulerFactory::createFileBased() creates JSON state, file-lock, and JSONL history repositories under state/, locks/, and history/. SchedulerFactory::createInMemory() creates process-local repositories. Both return the scheduler, status provider, history repository, and state repository in a SchedulerServices value object.

The following example uses application-specific implementations of the job-definition provider and child-process entry point:

use AdachSoft\Scheduler\Clock\SystemClock;
use AdachSoft\Scheduler\Execution\ProcessJobExecutor;
use AdachSoft\Scheduler\Schedule\DailyAtSchedule;
use AdachSoft\Scheduler\SchedulerFactory;
use AdachSoft\Scheduler\Worker\SchedulerWorker;
use AdachSoft\Scheduler\Worker\WorkerStopSignal;
use AdachSoft\SchedulerContracts\Definition\JobDefinitionDto;
use AdachSoft\SchedulerContracts\Definition\JobPolicyDto;
use AdachSoft\SchedulerContracts\Job\JobId;

$clock = new SystemClock();
$definition = new JobDefinitionDto(
    id: new JobId('pricing.sync'),
    schedule: DailyAtSchedule::fromString('03:00'),
    policy: new JobPolicyDto(
        timeoutSeconds: 300,
        killGraceSeconds: 10,
        retryDelaySeconds: 3600,
        overdueGraceSeconds: 7200,
        failureThreshold: 3,
        historyRetentionDays: 30,
    ),
    description: 'Synchronize pricing data.',
);
$definitions = new ApplicationJobDefinitionProvider([$definition]);
$executor = new ProcessJobExecutor(
    commandPrefix: [PHP_BINARY, __DIR__ . '/scheduler-child.php'],
    clock: $clock,
);
$services = SchedulerFactory::createFileBased(
    definitions: $definitions,
    executor: $executor,
    directory: '/var/lib/my-app/scheduler',
    clock: $clock,
);

$worker = new SchedulerWorker($services->scheduler, $clock);
$worker->run(WorkerStopSignal::listen());

ApplicationJobDefinitionProvider and scheduler-child.php are application-owned: the provider implements JobDefinitionProviderInterface, and the child entry point resolves the requested job and emits the result protocol shown above.

Symfony integration

For service registration, worker and tick commands, manual job execution, and status commands, use adachsoft/scheduler-symfony-bundle.