PHP Cli关键事件监听器功能

时间:2015-02-24 17:12:04

标签: php command-line

我正在制作 php cli 应用程序,其中我需要关键事件监听器

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

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

完成邮件发送后,我必须使用以下代码保持连接活动,以便接收送达回执。

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

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

连接在任何活动期间自动保持活动状态,但在空闲时我必须保持上面的循环运行。

如何按下任何会导致此事件中断并执行某些功能的键来运行事件?

1 个答案:

答案 0 :(得分: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();

另一种方法是通过不同脚本中的队列执行任务。有一些Queue Server,但可以通过PHP.exe简单地调用shell_execute你的队列脚本。在Linux上,你需要像...script.php > /dev/null 2>/dev/null &,Windows start /B php...这样的东西来停止等待脚本完成。