Answer the question
In order to leave comments, you need to log in
How to make every second timer in php?
I need a timer every second (to calculate how long the "pump" is running), can someone help? I sit and wonder all day.
Answer the question
In order to leave comments, you need to log in
Remember the start time and calculate dynamically by subtracting this time from the current time.
Take any implementation of Event Loop for PHP - ReactPHP or Swoole.
$loop = React\EventLoop\Factory::create();
$loop->addPeriodicTimer(1, function () {
$now = date('H:i:s');
$newStatus = Pump::getStatus();
$runTimer = PumpStatusStorage::getValue();
if ($runTimer > 0 && $newStatus === Pump::STOPPED) {
$time = time() - $runTimer;
echo "{$now}: Pump stopped, worked {$time}s\n";
PumpStatusStorage::setValue(null);
} else if ($runTimer === null && $newStatus === Pump::RUN) {
echo "{$now}: Pump started ... \n";
PumpStatusStorage::setValue(time());
}
});
$loop->run();
19:08:12: Pump started ...
19:08:23: Pump stopped, worked 11s
19:08:25: Pump started ...
19:08:30: Pump stopped, worked 5s
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question