PHP
How to implement a central clock for a Laravel web application?
Quizzes, time tracking, online education, Pomodoro timers, auctions, and many other web applications need a central clock.
The time on this clock is what all users see on their web page.
Such a central clock has to be implemented at the server, as this is the only place where we can rely on. It needs to be transmitted to the user's web page.
Use ReactPHP to implement a timer, either periodic,
$timer = $loop->addPeriodicTimer($time, function() use(&$task) {
broadcast(new TimeSignal(json_encode(...)));
});
or one time,
$timer = $loop->addTimer($time, function() use(&$task) {
broadcast(new TimedEvent(json_encode(...)));
});
where TimeSignal
and TimedEvent
are Laravel events.
Events are broadcast using Laravel Echo Server, Laravel Websockets, or Soketi. Say on a channel time
.
Listen for events with Laravel Echo,
window.Echo.channel('time')
.listen('TimeSignal', (e) => {
})
.listen('TimedEvent', (e) => {
});
Define in the Livewire component the listeners:
protected $listeners = [
'echo:time,TimeSignal' => 'processTimeSignal',
'echo:time,TimedEvent' => 'processTimedEvent',
];
Yoram Kornatzky