2012-02-11 24 views
3

我想每5分鐘運行我的php腳本。這是我的PHP代碼。沒有cron的PHP調度器

function call_remote_file($url){ 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_exec($ch); 
curl_close($ch); 
} 
set_time_limit(0); 

$root='http://mywebsiteurl'; //remote location of the invoking and the working script 

$url=$root."invoker.php"; 
$workurl=$root."script.php"; 

call_remote_file($workurl);//call working script 
sleep(60*5);// wait for 300 seconds. 
call_remote_file($url); //call again this script 

我運行這段代碼一次。即使在關閉整個瀏覽器窗口之後,它仍能正常工作。

問題是停止工作,如果我打開我的系統的互聯網連接。

如何解決這個問題。請幫助我。

+2

你想每5分鐘執行一次腳本嗎?爲什麼不是一個cron工作? – Josh 2012-02-11 07:37:47

+2

爲什麼不cron?我不明白你爲什麼驚訝,如果你的計算機沒有連接到網絡,它會停止從你的計算機調用腳本。 – 2012-02-11 07:38:02

+0

我的猜測是他/她無法訪問主機上的cron。 – 2012-02-11 07:39:55

回答

1

雖然我不會真的建議這樣做的東西,重要的(你將有穩定性問題),這可能是工作:

function call_remote_file($url){ 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_exec($ch); 
curl_close($ch); 
} 
set_time_limit(0); 


$root='http://mywebsiteurl'; //remote location of the invoking and the working script 

$url=$root."invoker.php"; 
$workurl=$root."script.php"; 

while(true) 
{ 
    call_remote_file($workurl);//call working script 
    sleep(60*5);// wait for 300 seconds. 
} 

另一種方法是使用命令行調用它exec()

function call_remote_file($url){ 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_exec($ch); 
curl_close($ch); 
} 
set_time_limit(0); 


$root='http://mywebsiteurl'; //remote location of the invoking and the working script 

$url=$root."invoker.php"; 
$workurl=$root."script.php"; 

call_remote_file($workurl);//call working script 
sleep(60*5);// wait for 300 seconds. 
exec('php ' . $_SERVER['SCRIPT_FILENAME']); 

如果可能的話,你應該真的使用cron。

1

上面的代碼是好的,但如果你想添加多個腳本在不同的時間間隔運行,則編碼變得更爲複雜。

如果您嘗試phpjobscheduler(開源所以免費使用),它提供了一個接口來添加,修改和刪除腳本運行。