0

I have a function where you can check the status of orders with all orders that have status 1 and the last update was more than 5 days ago and will be canceled and send an email.

I thought about entering a page and that page starts to execute a loop, but shortly after closing the web page it stops running the function and stops making updates to the database, that is, it doesn't run anything.

this is my code:

$x = 0;
while ($x < 3) {

    $x = $x + 1;
    $dias1 = \Carbon\Carbon::today()->subDays(5);
    $dias2 = \Carbon\Carbon::today()->subDays(15);

    $encomendasnaopagas = encomendas::where('estado', 1)->where('updated_at', '<', $dias1)
        ->join('distritos', 'encomendas.distrito', '=', 'distritos.id')
        ->update(['estado' => 5]);
    sleep(5);


    **code to email *** //I don't put it because it's unnecessary code

 $x = $x - 1;
}

it works, makes updates whenever I change the values in the database from 5 to 5 seconds but if you close the browser it stops, and I wanted it to be always running after starting it

Jsowa
  • 9,104
  • 5
  • 56
  • 60
  • 3
    Hey, in laravel you can run code in the background and at specific times with: https://laravel.com/docs/7.x/scheduling – Roland Starke Sep 08 '20 at 15:12
  • PHP has max execution time for scripts which is set to 30 seconds by default. You must check other solutions, look at my answer. – Jsowa Sep 08 '20 at 17:24
  • You need to create Cron job - script running at the equal specified time intervals. Example explanation: https://stackoverflow.com/questions/18737407/how-to-create-cron-job-using-php In Laravel you can also use Task scheduling, which is an adapter for cron. https://laravel.com/docs/7.x/scheduling – Jsowa Sep 08 '20 at 15:40

1 Answers1

0

You will need a Job script for that and run it with supervisord (PHP Command Line).

Here's an example of a simple Job script.

/**
 *
 * Example of creating simple Jobs in PHP that can be kept alive with Supervisord
 *
 * The idea is to keep your logic within an endless loop and make the script sleep for several seconds/minutes within that loop.
 *
 */

if (!empty($_SERVER['DOCUMENT_ROOT'])){
    die('Can only be run with PHP CLI!');
}

while(true) {

    echo date("Y-m-d H:i:s") . ": Running steady!\n";

    sleep(10);

}

Next you'll have to tell supervisor to keep this script running or restart it on failure. Below is an example. You'll have to consult the supervisor documentation for the settings best suitable to you.

/**
 *
 * Example of the corresponding Supervisord worker settings (Local environment)
 *
 * /etc/supervisor.d/test-worker.conf
 *
 */

[program:test-worker]
command=php /var/www/website/jobs/test.job.php
process_name=%(program_name)s_%(process_num)02d
numprocs=1
priority=999
autostart=true
autorestart=true
startsecs=1
startretries=3
user=apache
redirect_stderr=true
stdout_logfile=/var/www/website/worker-test.log
feskr
  • 759
  • 6
  • 10