Ankit Pise
Ankit Pise

Reputation: 1259

PHP Cli key event listener function

I am making php cli application in which I need Key Event listener

let's say this is my code Task To do

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

Once I'm done with sending messages, I will have to keep connection alive with following code to receive delivery receipts.

I use $command = fopen ("php://stdin","r"); to receive user commands.

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

Connection is automatically kept alive during any activities but on idle i have to keep above loop running.

How can I run the event on pressing any key which will make this event break and execute some function?

Upvotes: 0

Views: 946

Answers (1)

Christian Gollhardt
Christian Gollhardt

Reputation: 17034

PHP is not developed, to handle this kind of problems. The Magic Word would be Thread

The Cleanest way, I can Imagine, is taking a look into the Extension PThreads. With it, you can do Threads like in other Language:

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();

The other way would be to do tasks via a queue in a different script. There are some Queue Server out there, but it can be done simple calling shell_execute your Queue Script via PHP.exe. On Linux you need something like ...script.php > /dev/null 2>/dev/null &, Windows start /B php..., to stop waiting on Script is finished.

Upvotes: 1

Related Questions