PHP虽然循环在两小时后停止

时间:2017-03-23 17:38:42

标签: php

我有以下脚本,每60秒循环一次。一切正常,但两三个小时后脚本停止。我不明白为什么。

<?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);
}

使用以下命令执行PHP脚本:

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

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您可以将其包装在bash脚本中并完全删除while循环。

脚本&#34;包装&#34;:

#!/bin/bash

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

然后只需调用该脚本:

sudo -u root wrapper &