如何让工人在 PHP - Heroku 中连续 运行?

How to make the worker continuously run in PHP - Heroku?

我正在创建一个 php 应用程序,它在 heroku 中每 10-20 次自动将记录插入数据库中,以实现我已经创建了一个 proc 文件并且我在其中使用了 worker。在 heroku 中部署应用程序时发现 运行 工作人员 我是这个 heroku 的新手 PHP。任何人都可以帮助我了解这是什么意思以及我如何解决它并使工作人员 运行 不断地将记录插入数据库中。

这是我的 proc 文件中包含的行,位于项目的根目录下

worker: php /app/worker/db_worker.php

我的db_worker.php:

<?php
    include_once "./db_config.php";
        $conn = $connection;
        $number_1 = rand(1,50);
        $number_2 = rand(60,500);
        
        $insertQuery = "INSERT INTO random_numbers (num_1, num_2) VALUES ('".$number_1."', '".$number_2."')";
        $result = mysqli_query($GLOBALS['conn'], $insertQuery);
        if($result) {
            echo 'Details saved';
            
        } else {
            echo 'Failed to save details';
        }
?>

最简单的解决方案是 运行 循环操作。例如,

<?php
while (true) {
        // assume this can be included repeatedly
        include_once "./db_config.php";

        $conn = $connection;
        $number_1 = rand(1,50);
        $number_2 = rand(60,500);
        
        $insertQuery = "INSERT INTO random_numbers (num_1, num_2) VALUES ('".$number_1."', '".$number_2."')";
        $result = mysqli_query($GLOBALS['conn'], $insertQuery);
        if($result) {
            echo 'Details saved';
            
        } else {
            echo 'Failed to save details';
        }


        // recommend to do some memory clean up
        // ...
        
        // wait for 5 seconds
        sleep(5);
}

但是有一个问题。 PHP 不被认为是内存安全的。可能存在内存泄漏问题 运行 长时间使用它。如果效果不佳,您可以借助 cron-job.org.

等调度程序服务将其作为静态脚本简单地执行