PHP CLI继续每2秒检查一次MYSQL数据库,直到用户决定退出

PHP CLI继续每2秒检查一次MYSQL数据库,直到用户决定退出,php,Php,我在互联网上找不到太多关于PHP CLI的信息,所以我很难弄清楚如何完成我的代码 基本上,应用程序应该每2秒继续检查MYSQL数据库而不退出,除非用户输入字母“q” 在实现MYSQL之前,我只是连续打印“pro”一词,因此我的代码如下所示: <?php fwrite(STDOUT, "This should print word 'pro' continuously\n"); fwrite(STDOUT, "\tto exit, simply press 'q' and e

我在互联网上找不到太多关于PHP CLI的信息,所以我很难弄清楚如何完成我的代码

基本上,应用程序应该每2秒继续检查MYSQL数据库而不退出,除非用户输入字母“q”

在实现MYSQL之前,我只是连续打印“pro”一词,因此我的代码如下所示:

<?php
    fwrite(STDOUT, "This should print word 'pro' continuously\n");
    fwrite(STDOUT, "\tto exit, simply press 'q' and enter\n");

    do {
        fwrite(STDOUT, "pro\n");
    }while (fgetc(STDIN) != 'q');
?>
<?php

  // Do all your init work here, connect to DB etc
  $tickerSecs = 2;
  echo "Hello! I've started\n";

  do {

    // Do actual work here
    echo "I'm polling the database\n";

    // See stream_select() docs for an explanation of why this is necessary
    $r = array(STDIN);
    $w = $e = NULL;
    if (stream_select($r, $w, $e, $tickerSecs) > 0) {
      // The user input something
      echo "You input something\n";
      $char = fread(STDIN, 1);
      if ($char == 'q') {
        // The user pressed 'q'
        echo "You told me to quit\n";
        break;
      } else {
        echo "I don't understand '$char'\n";
      }
    }

  } while (TRUE); // Loop forever

  // Do shutdown work here
  echo "I'm shutting down\n";

当用户输入“q”时,应用程序会终止,但问题是它只打印“pro”一次,当我按enter键时。

fgetc()
将阻塞,直到有数据要读取-换句话说,当脚本到达
fgetc()
调用时,执行将停止,直到用户输入一些内容

为了解决这个问题,您需要检查是否有任何数据可以使用。您还可以使用
stream\u select()
将MySQL轮询限制为每2秒一次。基本框架如下所示:

<?php
    fwrite(STDOUT, "This should print word 'pro' continuously\n");
    fwrite(STDOUT, "\tto exit, simply press 'q' and enter\n");

    do {
        fwrite(STDOUT, "pro\n");
    }while (fgetc(STDIN) != 'q');
?>
<?php

  // Do all your init work here, connect to DB etc
  $tickerSecs = 2;
  echo "Hello! I've started\n";

  do {

    // Do actual work here
    echo "I'm polling the database\n";

    // See stream_select() docs for an explanation of why this is necessary
    $r = array(STDIN);
    $w = $e = NULL;
    if (stream_select($r, $w, $e, $tickerSecs) > 0) {
      // The user input something
      echo "You input something\n";
      $char = fread(STDIN, 1);
      if ($char == 'q') {
        // The user pressed 'q'
        echo "You told me to quit\n";
        break;
      } else {
        echo "I don't understand '$char'\n";
      }
    }

  } while (TRUE); // Loop forever

  // Do shutdown work here
  echo "I'm shutting down\n";

您可以使用pcntl_signal()为SIGQUIT(即Ctrl-C)注册处理程序,而不是在按下Q时停止。

上面给出的代码只是一个检查连续进程的示例。我还没有实现MySQL,所以很容易调试