Search code examples
phpherokuweb-worker

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


I am creating a php application which inserts the record in the DB for every 10 - 20 automatically in heroku to achieve that i had created a proc file and i'm using worker inside that . While deploying the application in the heroku there is found out while running the worker enter image description here I am new to this heroku and PHP. Can any one help me on what this mean and how can i resolve it and make the worker run continuously to insert the record in the Database.

This is line in my proc file contains which is under root of the project

worker: php /app/worker/db_worker.php

My 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';
        }
?>

Solution

  • The simplest solution would be to run your operations in a loop. For example,

    <?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);
    }
    

    But there's a problem. PHP is not considered memory safe. There can be memory leak issue(s) running it for really long time. If this didn't work well, you might simply do this as a static script with the help of scheduler services like cron-job.org.