0

I have a long running PHP script that looks something like this:

$myClass->myFunction('this takes 30 minutes to run');

I want to send a heartbeat every 30 seconds during the running of myFunction() to alert my application that the script is still running and did not fail.

In JavaScript, I can achieve this with setInterval(). I want to be able to do the same thing in PHP. Perhaps with a custom setInterval() function that looks like:

setInterval(function(){
    $myClass->addHeartbeat("still running");    
}, 30000);

Is this possible given the synchronous nature of PHP?

Lloyd Banks
  • 35,740
  • 58
  • 156
  • 248
  • Use [`sleep()`](http://php.net/manual/en/function.sleep.php) – Jay Blanchard Mar 30 '15 at 20:41
  • You cannot really do this with javascript considering it's single threaded. – Cthulhu Mar 30 '15 at 20:42
  • do not use `sleep()`.. that pauses the whole script.. – CrayonViolent Mar 30 '15 at 20:42
  • 2
    http://stackoverflow.com/questions/70855/how-can-one-use-multi-threading-in-php-applications – Barmar Mar 30 '15 at 20:44
  • @Barmar: good sh*t. I've been looking for this example. – unixmiah Mar 30 '15 at 20:47
  • Using an event loop, you can create a timer event that gets executed every X seconds. Using [LibEV](http://software.schmorp.de/pkg/libev.html) and [PHP extension](https://github.com/m4rw3r/php-libev) to interact with it, the code becomes pretty trivial. It's much easier than threading example, and since you already have a daemon - I assume that using the event loop would be quite easy. – N.B. Mar 30 '15 at 21:09

1 Answers1

-1

There isnt any easy way of doing this, but since you have a long running php script you can do something like this, assuming you have a main loop.:

while($running) { // long running main loop

    if(time() % 30 == 0) {
        $myClass->addHeartbeat("still running");
    }
    // your long running phpscript code
}
Patrik Grinsvall
  • 584
  • 1
  • 4
  • 22
  • 4
    But this will never execute the rest of the code in the script, it will just get stuck in this loop. – Barmar Mar 30 '15 at 20:44