php - 使用 PHP 和计时器启动和终止后台 python 脚本

标签 php python mysql timer

我要做的有点复杂。

我有一个 python 脚本,我想从 PHP 运行它,但在后台运行。我曾在某处看到,为了在后台运行 python 脚本,我必须使用 PHP 命令 exec(script.py) 来运行而不等待返回:到目前为止没有问题。

第一个问题:

我必须用另一个 PHP 命令停止这个循环脚本,该怎么做?

第二个问题:

我必须实现一个服务器端计时器,它会在时间结束时停止脚本。

我找到了这段代码:

<?php
$timer = 60*5; // seconds
$timestamp_file = 'end_timestamp.txt';
if(!file_exists($timestamp_file))
{
  file_put_contents($timestamp_file, time()+$timer);
}
$end_timestamp = file_get_contents($timestamp_file);
$current_timestamp = time();
$difference = $end_timestamp - $current_timestamp;

if($difference <= 0)
{
  echo 'time is up, BOOOOOOM';
  // execute your function here
  // reset timer by writing new timestamp into file
  file_put_contents($timestamp_file, time()+$timer);
}
else
{
  echo $difference.'s left...';
}
?>

来自 this回答。

那么,有没有办法在MySQL数据库中实现呢? (与脚本停止的集成不是问题)

最佳答案

其实很简单。您可以使用内存对象缓存系统。我会推荐 memcachedmemcached 中的内存对象可以从系统中的任何位置按字面意义进行访问。唯一的要求是支持与 memcached 后端服务器的连接。 (PHP 可以,Python 可以,等等)

回答您的第一个问题:

memcached 数据库中创建一个名为 stopme 的变量,其值为 0

从您的 python 脚本连接到 memcached 数据库并永久读取变量 stopme。假设当变量 stopme 的值为 0 时,python 脚本正在运行。

为了从 PHP 停止您的脚本,请从您的 PHP 脚本连接到 memcached 服务器并将 stopme 设置为 1。

python 脚本立即收到更新后的值并退出。

第二个问题的答案:

这可以像我之前在回答中解释的那样通过读取共享变量来完成,但另外我想提一下,您也可以使用 cronjob 来终止正在运行的脚本。

关于php - 使用 PHP 和计时器启动和终止后台 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41408486/

相关文章:

python - Django 模型类装饰器

python - 有使用 Pypy 的大项目吗?

python - Google App Engine 抛出此 InvalidURL ("nonnumeric port: ' %s'"% host[i+1 :]) exception when I try to deploy. 如何修复它?

java - 从 Eclipse 连接到 MySQL

PHP 将 mysql 转换为 mysqli

php - 我如何使用 PDO 和 memcached 设计缓存系统?

mysql - 数据库可以被完全覆盖 n 次而不会有截断数据的危险吗?

php - 查询为空错误|尝试获取特定的 Mysql 值

php - 从 mysql 回显特殊字符

PHP range() 从 A 到 ZZ?