2013-01-04 25 views
8

我不得不建立一個PHP隊列系統,並且發現這篇輝煌的文章 http://squirrelshaterobots.com/programming/php/building-a-queue-server-in-php-part-1-understanding-the-project/我用它來創建一個PHP隊列系統,它非常容易設置和使用。如何建立一個PHP隊列系統

下面是從shell(puTTy或somesuch)運行的queue.php的代碼。

<?PHP 

//. set this constant to false if we ever need to debug 
//. the application in a terminal. 
define('QUEUESERVER_FORK', true); 

//////// fork into a background process //////// 
if(QUEUESERVER_FORK){  
    $pid = pcntl_fork(); 
    if($pid === -1) die('error: unable to fork.');  
    else if($pid) exit(0);   
    posix_setsid();  
    sleep(1);   
    ob_start(); 
} 

$queue = array(); 

//////// setup our named pipe //////// 
$pipefile = '/tmp/queueserver-input'; 

if(file_exists($pipefile))  
    if(!unlink($pipefile))   
     die('unable to remove stale file'); 

umask(0); 


if(!posix_mkfifo($pipefile, 0666))  
    die('unable to create named pipe'); 

$pipe = fopen($pipefile,'r+'); 

if(!$pipe) die('unable to open the named pipe'); 

stream_set_blocking($pipe, false); 

//////// process the queue //////// 
while(1){  

    while($input = trim(fgets($pipe))){   
     stream_set_blocking($pipe, false);   
     $queue[] = $input;  
    }  

    $job = current($queue);  
    $jobkey = key($queue);  

    if($job){   
     echo 'processing job ', $job, PHP_EOL;     
     process($job);     
     next($queue);   
     unset($job, $queue[$jobkey]);    
    }else{   
     echo 'no jobs to do - waiting...', PHP_EOL;   
     stream_set_blocking($pipe, true);  
    }   

    if(QUEUESERVER_FORK) ob_clean(); 

} 

?> 

最難的部分是讓pcntl函數在我的服務器上工作。

我的問題是「如果服務器必須重新啓動,我該如何自動啓動作業?」

+1

什麼,確切地說,_你的問題? –

+1

@MartinBean如何在服務器重啓時自動啓動作業? –

+1

您可以修改服務器啓動腳本來執行此操作,也可以添加將報告腳本/服務器狀態的腳本,以及重新啓動作業的第二個腳本,然後使用它們從本地或遠程主機監視服務器/重新啓動作業(使用cronjob ) – llamerr

回答

9

我的問題是「如果服務器必須重新啓動,如何自動啓動作業?」

通過將其添加到服務器啓動時啓動的事件列表中。不幸的是,操作系統和操作系統版本的操作說明差異很大。你可能想要使用稍微更多的跨平臺的東西。我對supervisor有很大的好運,您可以在您選擇的操作系統的軟件包倉庫中找到它。

這就是說,你要走的路線瘋狂。你正在做的事情已經完成,更好的是,真棒的人。檢查出Gearman工作隊列系統和同步PECL extension。這種情況發生時,主管對於讓Gearman員工保持活力非常方便。