Home » Php » PHP Infinite script with Laravel

PHP Infinite script with Laravel

Posted by: admin November 29, 2017 Leave a comment

Questions:

I have a table users that I need to upload continuously, so once updated, I would like to relaunch the command directly.

Actually, I’m using a cron that launch itself each minute with Laravel ($schedule->command('update:users')->everyMinute();), but I’m losing some time if the job is quicker than one minute of I will overload my server if it is more than one minute.

I was thinking to maybe use a queue, and once the script terminated, relauch itself, like this:

// Do My stuff
Queue::push(new UpdateUsers($));

But if the script crash, it will not reload itself, and I need to launch it at least once. I know that I could use a pcntl_fork function, but I would like to have a turnkey function with Laravel. How should I do ?

Answers:

I would suggest running a Command the Cli,
in the command place a

while (true)

loop so it will run forever. After you created this script you can run it with supervisord

this service runs the command you tell him, and when it fails it will relaunch it automaticlly. Just be aware that after X failures it will stop, it depends on how you configured it.

Example for conf file in:

/etc/supervisord/conf.d/my_infinite_script.conf

and contents could be:

[program:laravel_queue]
command=php artisan your_command:here
directory=/path/to/laravel
autostart=true
autorestart=true
stderr_logfile=/var/log/your_command.err.log
stdout_logfile=/var/log/your_command.out.log

Questions:
Answers:

I’ve used the approach suggested by Tzook Bar Noy in some cases, but have also used a slightly uglier method which can avoid issues with having scripts looping forever if this might cause problems. This can be called every minute in a cronjob:

$runForSeconds = 55;
$runMinute = date('i');
do {
    ....code....
} while (date('i') == $runMinute && intval(date('s')) < $runForSeconds);

But the best solution would be to use a Jobs queue and run that using supervisor and:

command=php artisan queue:listen