G
G
grenline1231232021-06-13 18:44:26
PHP
grenline123123, 2021-06-13 18:44:26

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

3 answer(s)
D
Dmitry Nesterov, 2021-06-13
@nesterov02

This can only be done with JS

S
SagePtr, 2021-06-13
@SagePtr

Remember the start time and calculate dynamically by subtracting this time from the current time.

V
vilinyh, 2021-06-13
@vilinyh

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 question

Ask a Question

731 491 924 answers to any question