1

I have the following script, that loops every 60 seconds. All works fine, but after two or three hours the script stops. I have no idea why.

<?php

// The worker will execute every X seconds:
$seconds = 60;

// We work out the micro seconds ready to be used by the 'usleep' function.
$micro = $seconds * 1000000;

while(true){

    try {
        $url = 'URL';
        $fields = array(
            "hi"=> 1,
            "world"=> 2,
        );
        //url-ify the data for the POST
        foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
        $fields_string = rtrim($fields_string,'&');

        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_POST,count($fields));
        curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
        curl_exec($ch);

    } catch (Exception $e) {
        $myFile = "/usr/share/test/filephp.txt";
        $fh = fopen($myFile, 'a') or die("Can't open file");
        $stringData = "File updated at: " . time(). "\n";
        fwrite($fh, $stringData);
        fclose($fh);
    }




    // Now before we 'cycle' again, we'll sleep for a bit...
    usleep($micro);
}

The PHP script is executed with this command:

sudo -u root php -f /usr/share/test/test.php &

Any ideas?

6
  • Where are you running the above code? Commented Mar 23, 2017 at 17:40
  • 2
    PHP will stop executing after a predetermined time unless you run it as a daemon Commented Mar 23, 2017 at 17:42
  • 2
    It's probably because of max_execution_time setting. But why don't you just run it as a cron job instead of a continuous loop? Commented Mar 23, 2017 at 17:42
  • Running this is as root is a bit of a code smell. That shouldn't be necessary. Commented Mar 23, 2017 at 17:45
  • It's not "a bit of a code smell" it's a huge no-no! Commented Mar 23, 2017 at 17:58

1 Answer 1

1

You could wrap it in a bash script and remove the while loop altogether.

Script "wrapper":

#!/bin/bash

SECONDS=60
while [ 1 ]; do
    php -f /usr/share/test/test.php
    sleep $SECONDS
done

Then just call that script:

sudo -u root wrapper &
Sign up to request clarification or add additional context in comments.

2 Comments

It is as stable as it gets. You may need to use "nohup" to keep it from hanging up when the user session ends.
It's working. Thanks! I added "&" just after the "done"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.