Skip to content
componentaPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Componenta Scheduler

Independent PHP scheduling core with explicit time semantics, bounded catch-up, atomic occurrence staging and recoverable publication. The runtime depends only on PSR-20, not on a framework, queue, database or process supervisor.

Development preview: the included MemoryStore is process-local. Durable scheduling and cross-process coordination require a transactional store adapter. Do not use a new in-memory store on each invocation of system cron if schedule progress must survive restarts.

Requirements

PHP 8.4+ (64-bit), psr/clock:^1.0. No PHP extension beyond those supplied by standard PHP builds. PHP's timezone database determines calendar behavior.

Example

use Componenta\Scheduler\CallbackDispatcher;
use Componenta\Scheduler\CronSchedule;
use Componenta\Scheduler\MemoryStore;
use Componenta\Scheduler\MissedRunPolicy;
use Componenta\Scheduler\Occurrence;
use Componenta\Scheduler\OutboxPublisher;
use Componenta\Scheduler\PublishResult;
use Componenta\Scheduler\ScheduledTask;
use Componenta\Scheduler\Scheduler;
use Psr\Clock\ClockInterface;

$clock = new class implements ClockInterface {
    public function now(): DateTimeImmutable
    {
        return new DateTimeImmutable('now', new DateTimeZone('UTC'));
    }
};

$store = new MemoryStore($clock);
$scheduler = new Scheduler($store, $clock);

$registeredAt = $clock->now();
$startAt = $registeredAt->setTimestamp($registeredAt->getTimestamp());
$scheduler->register(new ScheduledTask(
    id: 'daily-report:v1',
    handler: 'report.generate',
    payload: '{"format":"csv"}',
    schedule: CronSchedule::daily(2, 30, new DateTimeZone('Europe/Stockholm')),
    missedRunPolicy: MissedRunPolicy::Latest,
), $startAt);

// A daemon or an external trigger calls tick repeatedly with the SAME store.
$report = $scheduler->tick(limit: 100, maxRunsPerTask: 20);

$dispatcher = new CallbackDispatcher(static function (Occurrence $run): void {
    // Resolve the application-owned handler alias and pass $run->id as the
    // idempotency key. Return only after confirmed downstream acceptance.
    echo $run->handler, ' ', $run->scheduledAt->format(DATE_ATOM), PHP_EOL;
});
$publisher = new OutboxPublisher($store, $dispatcher, leaseSeconds: 60);
for ($i = 0; $i < 100; ++$i) {
    $result = $publisher->publishOne();
    if ($result === PublishResult::Idle) {
        break;
    }
    if ($result === PublishResult::LeaseLost) {
        // Acceptance succeeded but acknowledgement did not. Monitor/reconcile.
        break;
    }
}

The demonstration callback prints a value; it is not a durable queue or an idempotent business handler. The store is intentionally kept alive across ticks.

Schedules

Type Meaning
OnceSchedule($at) One absolute instant.
IntervalSchedule($anchor, $seconds) Fixed elapsed seconds from an anchor; no drift or calendar interpretation.
CronSchedule($expression, $timezone) Five-field calendar cron with explicit timezone.
CronSchedule::daily/weekly/monthly(...) Convenience constructors over the same calendar rules.
CompositeSchedule($first, ...$others) Union of up to 64 direct members; equal instants produce a single run.
DateListSchedule(...$instants) Finite set of up to 10,000 input instants; sorts, deduplicates, and allows an empty set.
BoundedSchedule($schedule, $from, $until) Intersects any schedule with an inclusive absolute-time interval; either bound may be null.
ExcludedSchedule($schedule, ...$windows) Subtracts closed absolute-time exclusion windows without changing recurrence phase.

ScheduleInterface::nextRunAfter() is exclusive; previousRunAtOrBefore() is inclusive. The latter is necessary for efficiently coalescing a long backlog. Both are deterministic, side-effect-free and return the nearest occurrence or null on exhaustion of the supported domain. Collaborator failures and explicit search limits throw. Built-ins return native immutable UTC datetimes with whole-second precision. Queries may include fractional seconds. Registration and occurrence instants must be whole seconds. The supported UTC epoch is 1970-01-01 through 9999-12-31 inclusive. tick() samples a PSR-20 clock once.

Explicit date lists normalize all values to exact UTC seconds at construction. The readonly instants property is sorted and deduplicated; input count is limited before deduplication. Next/previous queries use binary search. Empty lists are valid and always exhausted. Bounded schedules normalize exact bounds, reject reversed intervals, include both endpoints only if the wrapped schedule has an occurrence there, and retain the original recurrence phase. A null bound means no additional restriction within the supported epoch. Queries in provably empty directions do not call the wrapped schedule; other collaborator errors (including search limits) propagate. Bounds are absolute instants, not local calendar dates, and do not collapse distinct DST-fold occurrences.

ExcludedSchedule takes up to 10,000 ExclusionWindow values. Each window has inclusive exact UTC-second endpoints; ExclusionWindow::instant($at) excludes a single instant. Empty input preserves the wrapped schedule. The readonly windows list is sorted, merged (including adjacent intervals) and canonical. A lookup jumps over whole excluded intervals instead of enumerating all their occurrences. Exclusions are absolute, so either occurrence of a repeated local time can be excluded separately. For local-date holidays, choose and convert the intended local boundaries explicitly. The decorator changes the occurrence set before missed-run policies apply; it does not cancel already staged occurrences or alter the phase of a recurring schedule.

use Componenta\Scheduler\ExcludedSchedule;
use Componenta\Scheduler\ExclusionWindow;

$schedule = new ExcludedSchedule(
    $schedule,
    ExclusionWindow::instant(new DateTimeImmutable('2026-12-25T01:30:00Z')),
    new ExclusionWindow(
        new DateTimeImmutable('2026-12-31T22:00:00Z'),
        new DateTimeImmutable('2027-01-01T04:59:59Z'),
    ),
);

Cron supports numbers, named months/weekdays, comma-separated lists, ascending ranges, *, */step, range steps and the documented standard calendar macros (@hourly, @daily, @midnight, @weekly, @monthly, @yearly, @annually). Sunday is 0 or 7. Both day predicates must match if either day field contains *; if neither contains *, the two day predicates are ORed. Other fields always intersect. By default missing local times are skipped and repeated local times yield both distinct UTC instants. Monthly day 31 skips shorter months. No shell commands, seconds field, wrapping ranges, L, W, #, ?, @reboot, or randomized fields. A step is 1..99 and applies only to * or an ascending range. Expressions are capped at 1024 bytes. Queries search at most one Gregorian 400-year cycle; if the search cannot prove exhaustion and finds no occurrence, SearchLimitException is thrown instead of falsely returning null.

Calendar offset transitions

Both the constructor and daily/weekly/monthly factories accept independent gapPolicy: CronGapPolicy and foldPolicy: CronFoldPolicy parameters.

Policy Meaning
CronGapPolicy::Skip (default) Omit nonexistent matching local times.
CronGapPolicy::AtTransition Map all matching missing local times in a forward jump to the first instant after the jump.
CronFoldPolicy::Both (default) Keep all distinct absolute representations of a matching repeated local time.
CronFoldPolicy::Earlier Keep only its earliest absolute representation.
CronFoldPolicy::Later Keep only its latest absolute representation.
CronFoldPolicy::Skip Omit ambiguous matching local times.

For example, CronSchedule::daily(2, 30, new DateTimeZone('Europe/Stockholm'), gapPolicy: CronGapPolicy::AtTransition, foldPolicy: CronFoldPolicy::Earlier) chooses a single occurrence on a spring-forward or fall-back day. Gap mapping is a set union: multiple missing wall times and a matching ordinary run at the same transition instant yield one UTC occurrence. It is not a shift of every missing wall time by the offset difference. Calendar predicates apply to the original missing wall time. Non-hour and date-line offset changes follow the same rules, whether or not a transition is labelled DST. Fixed offsets do not have gaps or folds. Both search directions use the same set of UTC instants. See contracts for bounds.

Missed runs

For the stored cursor c and the sampled observation time now, a run is due when its scheduled instant is <= now.

Policy Behavior
CatchUp Stage each due occurrence chronologically, at most maxRunsPerTask per tick.
Latest (default) Stage only the latest due occurrence; discard earlier unstaged ones.
Skip Require graceSeconds >= 0; discard runs strictly earlier than now - graceSeconds, stage remaining due runs chronologically within the limit.

Skip evaluates the grace window at each tick, not at actual execution time. A worker's start deadline, business retry policy and application idempotency belong to the worker/queue boundary. The grace value is not accepted for the other two policies. A skipped one-shot becomes exhausted. A pause preserves the cursor and existing outbox items; resume applies the selected missed-run policy. Pause does not cancel already accepted work.

State and delivery

ScheduleStoreInterface owns registration, pause/resume, ordered due snapshots and an atomic commit(SchedulePlan) operation. OutboxStoreInterface owns claim, acknowledge and delayed release. MemoryStore implements both against one state authority. A persistent implementation must commit schedule progress and outbox rows in the same transaction. The caller must not substitute a separate cache write followed by a broker publish.

Scheduler::tick() examines at most limit due schedules (1..1000), each at most once per call, and stages up to maxRunsPerTask (1..1000) per schedule. TickReport describes only successfully confirmed state changes. A competing commit or full outbox has no effect on that schedule and is counted separately. A thrown error aborts the remaining tick; earlier confirmed commits remain. A capacity rejection is batch-atomic, so reduce maxRunsPerTask when a store's free capacity cannot fit a batch. Due order is oldest cursor then binary task ID; there is no global fairness or cross-schedule execution ordering guarantee.

Registration lifecycle

Each registration has an application-chosen ID unique across all schedulers publishing to the same idempotency domain. A registration ID is a generation, not a reusable name. Duplicate registration (including retired IDs) returns false without changes; it is not an upsert.

  • status($id) distinguishes Unknown, Registered (active, paused or exhausted) and Retired; state($id) on the store returns a snapshot only for registered generations.
  • retire($id) permanently removes a registered generation from planning, frees its registration slot and retains a tombstone. Repeating retirement returns AlreadyRetired; an unknown ID returns Missing and is not reserved.
  • replace($oldId, $replacement, $startAt) atomically retires the old generation and registers a new, unused generation at revision zero. The new start and policy are independent; the replacement is not paused. Reusing the same ID is invalid. The same successor ID on a retry returns AlreadyReplaced even if the successor was subsequently retired. This confirms the historical transition, not equality of task contents or current activity.
  • Capacity means the tombstone budget cannot accommodate the transition; the source and target remain unchanged. DuplicateId on replacement means the target is registered or retired. Missing/Retired refer to the source.

The reference store retains tombstones for its lifetime (10,000 by default, configurable with retiredCapacity), separately from the registration capacity. Tombstones contain only the ID and optional successor ID, not task payloads or schedules. There is intentionally no unsafe tombstone eviction or ID reuse. Replacement works at full registration capacity because the registered count is unchanged. Failed cursor computation has no lifecycle effects from the core.

Retirement and replacement invalidate stale plans but do not recall previously staged or published occurrences. Old and new generations have distinct run IDs, including at the same instant; choose the replacement start time accordingly. Cancellation of accepted work and mutual exclusion across generations must be implemented at the actual execution boundary. See the lifecycle contract.

Occurrence snapshots handler alias, opaque payload, scheduled instant and a stable SHA-256 ID derived from the versioned task ID and scheduled UTC second. It contains no arbitrary PHP executable or class name resolution. Use a trusted handler registry in an adapter. Payload is limited to 1 MiB per registration.

A claim uses an opaque token and a store-authoritative microsecond deadline. Acknowledgement and release require that the token still owns an unexpired claim. At the exact expiry instant it is stale. An expired or explicitly released item can be claimed again under a fresh token with the same occurrence ID. Delivery::$attempt counts acquisitions, starting at one, including claims lost to crashes. Release preserves the counter. renew($delivery, $leaseSeconds) extends the live lease to the greater of its current deadline and store time plus the requested duration, returning a fresh immutable snapshot or null for stale ownership. It neither increments attempts nor rotates the acquisition token; old snapshots of that acquisition remain valid until release, acknowledgement or expiry. The actual deadline is store-owned, not the snapshot property. Renewal is cooperative: callers using the store directly can renew; OutboxPublisher::publishOne() does not automatically renew while a dispatcher is running. OutboxPublisher::publishOne() returns Idle, Published or LeaseLost. By default a dispatcher exception propagates unchanged and the claim expires for redelivery. A store exception can mean an unknown settlement. Published means acceptance AND acknowledgement, not completion of a business operation.

Deferred publication retry

To explicitly release a failed publication for another attempt after a delay:

$publisher = new OutboxPublisher(
    store: $store,
    dispatcher: $dispatcher,
    leaseSeconds: 60,
    retryPolicy: new FixedPublicationRetryPolicy(5),
);

Implement PublicationRetryPolicyInterface::delayAfterFailure() to classify errors and choose a delay from 0 to 604800 seconds, or return null to leave the current claim until expiry. The policy receives the immutable occurrence, acquisition attempt and original throwable, but no lease token. The delay is measured from the store's release time; no sleeping or inline retry occurs. A stale release never affects a newer claim. The original dispatcher exception is still thrown, including when the release succeeds. If the policy or release throws, PublicationRecoveryException preserves both original throwable instances in dispatchFailure and recoveryFailure. Claim and acknowledgement errors are not passed to the policy; no alternate settlement is attempted. A policy returning null does not disable redelivery. Use a bounded delivery profile and operator recovery to limit the number of acquisitions.

Bounded delivery and recovery

By default, the store does not limit publication attempts. Configure new MemoryStore($clock, maxDeliveryAttempts: 5) to allow at most five acquisitions per delivery cycle, counting expired and explicitly released claims. At the final acquisition the holder can still renew and acknowledge. If it expires or is released, the next eligible poll quarantines it instead of acquiring it again. A delayed release must first become eligible. The same poll can acquire another item; null means no acquisition, not no maintenance.

FailedOutboxStoreInterface exposes failure($occurrenceId) and bounded, binary-ID-ordered failures(afterId: ..., limit: ...) pages. A FailedOccurrence retains the original occurrence, a distinct failure ID, acquisition count and store-authoritative failure timestamp. It records an exhausted publication budget, not confirmed business failure or even confirmed non-delivery. There are no stored exception messages, traces or arbitrary diagnostics.

  • redrive($failure) atomically restores eligible work with the same occurrence ID and payload, resets the acquisition count and clears the previous lease.
  • discard($failure) deliberately deletes that failed generation. Both methods return false for missing or stale failure snapshots, including after redrive followed by a newer failure. Do not retry an uncertain settlement with a different failure identity. Inspect current state and reconcile first.
  • Pending and failed work share the configured outboxCapacity. Quarantine and redrive do not free capacity; successful acknowledgement or explicit discard do. Monitor both pendingCount and failedCount; a full store applies backpressure rather than silently deleting work.

The bound applies per delivery cycle; an explicit redrive starts a new one. A limited store requires continued polling and operator recovery of exhausted work. With maxDeliveryAttempts: null, the default behavior is unchanged.

Delivery is at-least-once under durable storage and continued polling (with recovery of exhausted work if bounded), not exactly-once execution. A crash or expired lease after successful acceptance can cause repeat publication. Consumers must deduplicate by occurrence ID (for example with Componenta Idempotency), and define their own retry/dead-letter policy. The memory reference does not survive process loss. It clamps observed lease time against clock rollback; if wall time goes backwards, expiration can be delayed until it catches up. The store rotates acquired items so a failing item cannot monopolize a finite eligible set.

NonOverlappingDispatcher is an optional local synchronous decorator. It rejects concurrent or reentrant calls for the same task through that instance, releases its guard on exceptions and does not guarantee exclusion across hosts, queue workers or different generations. The actual execution adapter must own cross-process overlap, fencing, lease renewal and start deadlines; publishing under a lease cannot guarantee that a remote worker has finished. The core never attempts to interrupt arbitrary PHP code.

MemoryStore performance

The reference adapter indexes active, non-exhausted schedule cursors. Small due queries traverse a bounded heap frontier, while larger requested fractions use native sorting; empty due queries do not scan registrations. The index is updated together with each state transition and does not change ordering, snapshot identity or the semantics of rejected plans. It costs additional memory and registration/update work; measure the actual workload. Outbox claims use separate indexes for waiting deadlines and ready rotation order. Empty polls do not scan all busy entries; after promotion, eligible entries retain insertion/rotation order, not deadline order. Renewal, release, quarantine and redrive maintain the indexes. Mass expiry may promote many entries in one poll; the index increases retained memory and may slow small uncontended workloads.

The standalone benchmark runs each profile in a separate process:

php -d opcache.enable_cli=0 benchmarks/MemoryStore.php due-empty 10000
php -d opcache.enable_cli=0 benchmarks/MemoryStore.php due-first 10000
php -d opcache.enable_cli=0 benchmarks/MemoryStore.php due-batch 10000
php -d opcache.enable_cli=0 benchmarks/MemoryStore.php busy-poll 10000
php -d opcache.enable_cli=0 benchmarks/MemoryStore.php sparse-claim 10000
php -d opcache.enable_cli=0 benchmarks/MemoryStore.php expire-drain 10000

See the measurements for before/after profiles and their limitations. No timing threshold is used as a correctness test.

For repeated isolated measurements using PHPBench (development dependency):

composer bench
composer bench:smoke

The full run measures schedules, planning and indexed storage operations at 1,000 and 10,000 entries. The smoke run uses one revolution/iteration per subject variant, without timing assertions. Destructive drain subjects require a fresh fixture per revolution: do not override their revolution count above one.

Adapter conformance

The optional Componenta\Scheduler\Testing namespace exposes portable, runner-independent store acceptance cases for core, bounded delivery and capacity profiles. See adapter testing for fixture requirements and additional real-storage verification.

Verification

php tests/run.php          # standalone, including independent reference models
composer install
composer test             # PHPUnit runs the same cases using real PSR-20
composer analyse          # PHPStan max
composer check
composer coverage        # requires PCOV or Xdebug
composer mutate          # Infection, requires a coverage driver

composer coverage checks all executable lines in src, including uncovered files and the portable conformance helpers, with a minimum of 95%. It emits Clover and HTML reports; composer coverage:check evaluates the existing report without rounding the comparison. Linux/PHP 8.4 CI runs the gate and retains reports even on a failed threshold. This is line coverage, not branch or path coverage.

composer mutate uses Infection's default mutation profile across all of src, including uncovered code, with minimum overall and covered-code MSI of 90%. Timeouts count as escaped. Full mutation testing is dispatched manually (or when the mutation workflow/configuration changes), rather than on every ordinary commit. It may exceed the CI time budget; an incomplete run is not a passing score. Reports are retained for review. See quality measurement.

The standalone fixture declares the PSR-20 signature for a dependency-free local run; it is not used as evidence of Composer dependency resolution. The exact executed checks and remaining release gates are in docs/verification.md. See the contract specification and research for design rationale.

License

MIT.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages