Skip to content
Belikhun edited this page Sep 15, 2026 · 1 revision

⏱️ Ticker

Ticker is blink's background work: tasks queued now and run later by a runner, and recurring entries started by a once-a-minute tick. It needs one cron line and one long-running process, and it works the same on MySQL and SQLite.

Tasks

namespace App\Task;

use App\Model\Invoice;
use Blink\Model;
use Blink\Ticker\Task;

class SendInvoice extends Task {
	public int $attempts = 3;
	public int $holdoff = 60;
	public int $timeout = 120;

	public function __construct(protected int $invoiceId) {}

	public function run(): void {
		Invoice::getByID($this -> invoiceId, Model::MUST_EXIST) -> send();
	}

	public function failed(\Throwable $e): void {
		Invoice::getByID($this -> invoiceId) ?-> markUndeliverable();
	}
}
use Blink\Ticker;

Ticker::queue(new SendInvoice($invoice -> id));
Ticker::queue(new SendInvoice($invoice -> id), delay: 300);
Ticker::queue(new SendInvoice($invoice -> id), queue: "mail");

A task is serialized when queued and woken up when a runner reaches it, so it must survive serialize(). Hold ids rather than models: the row may have changed by the time the task runs.

Property or method Meaning
$attempts How many times to try before the task is failed. Default 1.
$holdoff Seconds to wait before the next attempt. Default 0.
holdoffFor(int $attempt) Override for a backoff sequence; returns seconds for that attempt
$timeout Seconds a run may take. 0 means the runner's default.
$queue Which queue. Null means CONFIG::$TICKER_QUEUE.
run() The work
failed(\Throwable $e) Called once, after the last attempt fails
key() A string that makes the task unique; see below
label() What ticker:status shows

Delivery

Delivery is at least once. A runner that dies mid-task leaves its claim to expire after CONFIG::$TICKER_RETRY_AFTER seconds, and another runner picks the task up. A task therefore has to be safe to run twice.

Claiming is optimistic and needs no transaction: a runner selects a candidate, updates it with a token where it is unclaimed or expired, and owns it only if exactly one row changed. The token guards the release and the delete too, so a runner that overran its claim cannot remove a task someone else has since taken.

Unique tasks

A task with a key() can be coalesced:

public function key(): ?string {
	return "reports:rebuild:{$this -> tenantId}";
}

Ticker::queueUnique(new RebuildReports($tenant -> id), delay: 60);  // no-op while one is waiting
Ticker::pullForward("reports:rebuild:7");                            // run the waiting one now
Ticker::forget("reports:rebuild:7");                                 // drop it

Failures

After the last attempt, the task moves to ticker_failures with the exception and the id of an error report. ticker:failed lists them, ticker:retry requeues one or all, ticker:forget --failures empties the list.

Runners

php core/blink ticker:run
php core/blink ticker:run lightrail
php core/blink ticker:run --once
php core/blink ticker:run --stop-when-empty
php core/blink ticker:run --max-tasks=1000 --max-time=3600 --memory=256 --sleep=3

A runner drains one queue: claim a task, run it, remove it or put it back. Between tasks it drops model instances, metrics and the Essence constructor stack, flushes the audit log, and collects garbage, so it can run for days.

Stop it with SIGTERM or Ctrl-C; the task in flight finishes first. ticker:restart asks every runner to stop after its current task, through a cache timestamp, which is the portable way to roll a deployment: start new runners, then ticker:restart.

Timeouts use pcntl_alarm where PHP has it and otherwise fall back to the claim expiry. Without pcntl (Windows, most notably) the runner prints a warning at start and timeouts are advisory.

Run several runners against one queue when one is not enough; the claim guarantees no task runs twice at once. MySQL is the recommendation past a single runner. SQLite works, and the queue keeps every write to one statement, but long transactions inside tasks block web writers.

No runner at all

CONFIG::$TICKER_STORE = "direct" runs every queued task inline, inside the request that queued it. The work still happens, the caller waits for it, and exceptions come straight back. For a small site with nowhere to put a process.

Recurring work

A module declares recurring entries in orbits():

use Blink\Ticker\Orbit;

public function orbits(Orbit $orbit): void {
	$orbit -> task(RebuildReports::class) -> everyDay("02:00") -> alone() -> name("reports.rebuild");
	$orbit -> task(PingUpstream::class) -> everyFiveMinutes() -> detached();
	$orbit -> command("trace:purge --force") -> everyDay("03:30");
	$orbit -> task(CloseMonth::class) -> cron("0 1 1 * *");
	$orbit -> task(WarmCache::class) -> everyMinute() -> when(fn () => !Maintenance::active());
}
Method Meaning
task($class), command($line) What to run: a task instance, or a console command line
everyMinute(), everyFiveMinutes(), everyTenMinutes(), everyFifteenMinutes(), everyThirtyMinutes()
everyHour($minute), everyDay("HH:MM"), everyWeek($weekday, "HH:MM"), everyMonth($day, "HH:MM")
cron("* * * * *") Any five-field pattern, @daily style macros included
alone($seconds = 3600) Skip a run while the previous one is still going, up to that long
detached() Queue the work as a task rather than running it inside the tick
when(callable) Run only when the callable says so
name($name) The name shown by ticker:orbits; defaults to the class or command

Patterns follow Vixie cron: *, numbers, a-b, */n, a-b/n, lists, month and weekday names, Sunday as both 0 and 7, and the day-of-month or day-of-week rule when both are restricted.

The tick

* * * * * cd /var/www/site && php core/blink ticker:tick >> /dev/null 2>&1

One cron line. ticker:tick computes the minute once, then claims each due entry with a single conditional update on ticker_orbits, so an entry runs exactly once per minute across as many hosts as are ticking, with no lock. It exits 0 even when an entry fails: the failure goes into the entry's row and an error report, and ticker:orbits --failing shows it.

orbits() is called on every tick, so it must stay cheap: build the entries and return.

Inspecting

php core/blink ticker:status              # queues and waiting tasks
php core/blink ticker:orbits              # entries, last run, last outcome
php core/blink ticker:failed
php core/blink ticker:retry 12
php core/blink ticker:clear mail --force

Configuration

Setting Default Meaning
CONFIG::$TICKER_STORE "database" database, or direct to run inline
CONFIG::$TICKER_QUEUE "default" The queue a task goes to when it names none
CONFIG::$TICKER_RETRY_AFTER 90 Seconds before a claimed task can be claimed again
CONFIG::$LIGHTRAIL_QUEUE "lightrail" Where background and batched event handlers go

Clone this wiki locally