schorsch3000 / tick
Tiny helper to run loops at a fixed interval without drift
Requires
- php: >=8.4
Requires (Dev)
- phpstan/phpstan: ^2.3
- phpunit/phpunit: ^12
- rector/rector: ^2.8
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
A tiny PHP library that keeps loops from running too often.
You tell Tick the minimum time you want between two iterations. It sleeps only for whatever part of that time your code hasn't already used up. If your loop body takes 0.3s and the interval is 1s, Tick sleeps 0.7s. If the loop body takes longer than the interval, it doesn't sleep at all.
$tick = new Tick(1.0); while (true) { pollSomething(); // takes 0.3s $tick->tick(); // sleeps the remaining 0.7s }
Typical uses: polling an API or a queue, worker and daemon loops, refreshing a status display, or anything else that should run "as often as possible, but not more than every N seconds".
Requirements
- PHP 8.4 or newer
- No other dependencies
Installation
composer require schorsch3000/tick
Usage
Blocking: sleep until the next iteration
use Schorsch3000\Tick\Tick; $tick = new Tick(0.5); // seconds, fractions allowed while (true) { doWork(); $tick->tick(); // returns once at least 0.5s have passed since the last tick }
Start right away
By default the timer starts when you create the object, so the first tick() waits a full interval. If the first iteration should run immediately, pass startImmediately: true:
$tick = new Tick(5, startImmediately: true); while (true) { $tick->tick(); // 1st call returns at once, then every call waits 5s doWork(); }
Non-blocking: check without sleeping
When your loop must not sleep, for example because it handles several jobs or waits on sockets, use tryTick(). It returns true and restarts the timer if the interval has passed, and returns false immediately otherwise.
$heartbeat = new Tick(10); $cleanup = new Tick(300); while (true) { handleIncomingRequests(); // does its own short waiting if ($heartbeat->tryTick()) { sendHeartbeat(); } if ($cleanup->tryTick()) { removeExpiredSessions(); } }
If you need to decide when the timer restarts, use canRun() and reset() separately. canRun() only checks; it never restarts the timer.
if ($tick->canRun()) { if (sendReport()) { $tick->reset(); // only count successful runs } }
One-off intervals
tick(), canRun() and tryTick() accept an optional interval that applies to that call only. That's handy for backing off after an error:
$tick = new Tick(1); while (true) { $ok = fetchUpdates(); $tick->tick($ok ? null : 30); // normally 1s, after a failure 30s }
To change the interval permanently, use setInterval().
How it behaves
- Minimum time, not a fixed rate. Each interval is measured from the moment the previous tick finished. If a tick runs late, the next one is not moved earlier to catch up. Ticks never come closer together than the interval, but over many iterations they slowly fall behind a wall clock schedule. If you need "exactly on every full minute", this is the wrong tool.
- Clock changes don't matter. Time is measured with PHP's monotonic clock (
hrtime). If the system clock is moved (NTP, daylight saving, a manual change),Tickneither sleeps for hours nor skips a tick. - Signals don't end the wait early. If your process handles signals (for example with
pcntl_signal()) and one arrives whiletick()is sleeping, your handler runs andtick()goes back to sleep for the rest of the interval. - Invalid intervals throw. Intervals must be between
0and1e9seconds (about 31 years). Negative values,NANandINFthrow anInvalidArgumentException. An interval of0means "never wait".
API reference
| Method | What it does |
|---|---|
new Tick(float $interval, bool $startImmediately = false) |
Creates the timer. $interval is the default minimum time between ticks, in seconds. If $startImmediately is true, the first tick is due right away. |
tick(?float $interval = null): void |
Sleeps until the interval has passed since the last tick, then restarts the timer. |
tryTick(?float $interval = null): bool |
If the interval has passed: restarts the timer and returns true. Otherwise returns false immediately. |
canRun(?float $interval = null): bool |
Returns whether the interval has passed. Never restarts the timer. |
reset(): void |
Restarts the timer from now. |
setInterval(float $interval): void |
Changes the default interval. |
All methods that take an interval throw InvalidArgumentException for invalid values.
Development
make # format, rector, tests, phpstan (may rewrite files) make check # same checks without rewriting anything make test # tests only make coverage # needs pcov or Xdebug
More in docs/:
- Architecture: how
Tickworks and which behavior is intentional - Development: Makefile targets and tooling
- Testing: timing-based tests, the signal test, coverage
- Release: versioning and backwards compatibility
License
MIT, see LICENSE.