Skip to content

Scheduler

Class  ·  Sharkord\Scheduler

Class Scheduler

Named, cancellable timer registry built on top of ReactPHP’s event loop.

All timers are identified by a unique string name. Registering a new timer under an existing name silently cancels the previous one first, preventing duplicate timers from accumulating across reconnects or re-registrations.

Available as {@see \Sharkord\Sharkord::$scheduler} on the bot instance.

// Broadcast a message every 60 seconds.
$sharkord->on(\Sharkord\Events::READY, function() use ($sharkord): void {
$sharkord->scheduler->every(60.0, 'heartbeat', function() use ($sharkord): void {
$sharkord->channels->get('status')?->sendMessage('Still alive!');
});
});
// Cancel the timer later.
$sharkord->scheduler->cancel('heartbeat');

Scheduler constructor.

Parameters

ParameterTypeDescription
$loopLoopInterfaceThe ReactPHP event loop.

Registers a repeating timer that fires every N seconds.

If a timer with the given name already exists, it is cancelled before the new one is registered. The callback receives no arguments.

Parameters

ParameterTypeDescription
$secondsfloatInterval between invocations in seconds.
$namestringUnique identifier for this timer.
$callbackcallableThe function to invoke on each tick.

Example

$sharkord->scheduler->every(30.0, 'status-ping', function() use ($sharkord): void {
$sharkord->channels->get('general')?->sendMessage('Bot is running.');
});

Registers a one-shot timer that fires once after N seconds.

The timer is automatically removed from the registry once it fires. If a timer with the given name already exists, it is cancelled first.

Parameters

ParameterTypeDescription
$secondsfloatDelay before the callback fires in seconds.
$namestringUnique identifier for this timer.
$callbackcallableThe function to invoke once.

Example

// Send a reminder 5 minutes after the bot starts.
$sharkord->scheduler->after(300.0, 'startup-notice', function() use ($sharkord): void {
$sharkord->channels->get('general')?->sendMessage('Bot has been running for 5 minutes!');
});

Cancels a registered timer by name.

Does nothing if no timer with the given name is registered.

Parameters

ParameterTypeDescription
$namestringThe timer name to cancel.

Example

$sharkord->scheduler->cancel('status-ping');

Returns whether a timer with the given name is currently active.

Parameters

ParameterTypeDescription
$namestringThe timer name to check.

Returns bool

Example

if (!$sharkord->scheduler->has('status-ping')) {
$sharkord->scheduler->every(60.0, 'status-ping', $callback);
}

Returns the names of all currently active timers.

Returns string[]

Example

foreach ($sharkord->scheduler->active() as $name) {
echo "Active timer: {$name}\n";
}

Cancels all active timers.

Example

// Tear everything down cleanly on disconnect.
$sharkord->scheduler->cancelAll();