nexphant/scheduler
Timer-based task scheduler running directly in the event loop.
Install
composer require nexphant/schedulerBasic Usage
The task scheduler executes callbacks at intervals or scheduled times within the persistent runtime without spawning new OS processes.
use Nexphant\Scheduler\SchedulerRuntime;
$scheduler = new SchedulerRuntime();
// Execute every second
$scheduler->everySecond(function ($ctx) {
// Task logic
});
// Run at specific intervals (in seconds)
$scheduler->interval(30.0, function ($ctx) {
// Run every 30 seconds
});
// Run once with delay
$scheduler->delayed(10.0, function ($ctx) {
// Run once after 10 seconds
});
// Cron expression
$scheduler->cron('*/5 * * * *', function ($ctx) {
// Run every 5 minutes
});
// Start scheduler execution
$scheduler->start();start() runs until stop() is called. Each task receives a TaskOwner, so resources can be associated with the scheduled run and closed when it finishes.
Task Lifecycle and Overlap Control
Tasks run within a TaskOwner context passed as the first parameter. By default, tasks can run concurrently if execution takes longer than the interval. You can disable overlapping:
$scheduler->interval(10.0, function ($ctx) {
// Long running task
})->withoutOverlapping();Scheduler API
| Method | Description |
|---|---|
everySecond(callable $fn) | Runs the task every 1 second. |
everyMinute(callable $fn) | Runs the task every 60 seconds. |
interval(float $seconds, callable $fn) | Runs the task every N seconds. |
delayed(float $seconds, callable $fn) | Runs the task once after N seconds. |
cron(string $expression, callable $fn) | Runs the task using a Cron expression. |
withoutOverlapping() | Prevents the last defined task from overlapping its runs. |
cancel(int $taskId) | Cancels a task by its ID. |
start() | Starts the scheduler loop. |
stop() | Stops the scheduler loop. |
Runtime Integration
The scheduler can be reached from the runtime facade:
use Nexphant\Runtime\Runtime;
Runtime::schedule()
->everyMinute(fn ($task) => syncReports())
->withoutOverlapping();In CLI/Fiber runtime mode the scheduler sleeps cooperatively. Outside the runtime it falls back to standard process sleeps.
Cron Notes
The cron parser supports five fields: minute, hour, day, month, and weekday. A task is due when every field matches the current time. Use * for any value and */N for step intervals.
