【问题标题】:Start and terminate a background python script with PHP and a timer使用 PHP 和计时器启动和终止后台 python 脚本
【发布时间】:2023-03-19 23:44:01
【问题描述】:

我要做的有点复杂。

我有一个 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 数据库中实现呢? (与脚本停止集成没有问题)

【问题讨论】:

  • secure.php.net/manual/en/function.exec.php#89716 使用它来获取进程 ID,将其存储在文件或数据库中,然后稍后杀死具有该 ID 的进程。请记住,无论多么小,该进程可能已经停止,而另一个进程最终使用了该 ID(这意味着您正在杀死另一个进程)

标签: php python mysql timer


【解决方案1】:

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

回答您的第一个问题

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

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

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

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

回答你的第二个问题:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 2019-03-16
    相关资源
    最近更新 更多