gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 21:14:36 25 4
gpt4 key购买 nike

我在互联网上找不到太多关于 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');
?>

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

最佳答案

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

为了解决这个问题,您需要使用 stream_select() 检查是否有任何数据要读取.您还可以使用 stream_select() 将 MySQL 轮询限制为每 2 秒一次。一个基本框架看起来像这样:

<?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 + enter 而不仅仅是 q -我真的不明白这是为什么,也许其他人可以在这里提供缺失的部分?

关于PHP CLI 继续每 2 秒检查一次 MYSQL 数据库,直到用户决定退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11775797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com