2015-02-24 32 views
0

我正在PHP CLI应用程序中,我需要关键事件听众PHP CLI的关键事件侦听器功能

让我们说这是我的代码 任务做

for($i=0;$i<=n;$i++){ 
    $message->send($user[$i]); 
} 

一旦我我完成发送邮件,我将不得不保持连接活着与下面的代码接收送达收据。

我用$command = fopen ("php://stdin","r");来接收用户命令。

while(true){ 
    $connection->refresh(); 
} 

在任何活动期间连接都会自动保持活动状态,但在闲置时我必须保持循环运行。

如何在按下任何可以使此事件中断并执行某些功能的按键上运行事件?

+0

你可能真的想看看一些队列软件。尝试使用本地化的PHP进行守护进程并不会有任何乐趣。 – castis 2015-02-24 17:54:44

回答

1

PHP没有开发,来处理这类问题。魔术字将是Thread

我可以想象,最干净的方式是看看分机PThreads。有了它,你可以做线程像其他语言:

class AsyncOperation extends Thread { 
    public function __construct($arg){ 
    $this->arg = $arg; 
    } 

    public function run(){ 
    if($this->arg){ 
     printf("Hello %s\n", $this->arg); 
    } 
    } 
} 
$thread = new AsyncOperation("World"); 
if($thread->start()) 
    $thread->join(); 

另一种方式是通过在不同的脚本中的队列做任务。有一些队列服务器在那里,但它可以简单地通过PHP.exe调用shell_execute您的队列脚本。在Linux上,您需要诸如...script.php > /dev/null 2>/dev/null &,Windows start /B php...之类的东西来停止等待脚本完成。