关于PHP监听数据库的定时器

今天接触到一个项目, 需要在新增了数据之后监听字段, 如果超过 3 秒字段还不变化的话直接输出操作超时, 需要利用PHP完成一个实时监听数据

完成思路主要是每秒发送一个请求查询字符串是否变化, 当超过 3 秒或者字段变化时跳出循环, 以下是具体实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class packet
{
private $lastId;
private $DB;
...
private function verify()
{
$sql_select = 'SELECT count(*) FROM raw_command WHERE id=:id AND ack_time IS NOT NULL ;';
// 已封装的查询方法, 使用PDO的prepare方法, 预保留字段.
$data = $this->DB->selectQuery($sql_select, [':id' => $this->lastId]);
// 返回字段是否变化.
return count($data);
}
public function timeKey()
{
$i = 0;
while ($i != 3) {
if ($this->verify()) {
return true;
}
$i++;
sleep(1);// 等待1s
};
return false;
}
...
}

调用时, 直接调用 packet 的 timeKey 方法