Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel : Task Scheduling [ In Parallel ]

I have multiple tasks that need to be done every hour or two. All of them have been scheduled via Laravel using below comamnds as cron jobs

$schedule->command('email:notifications1')
            ->cron('15 * * * * *');
$schedule->command('email:notifications2')
            ->cron('15 * * * * *');
$schedule->command('email:notifications3')
            ->cron('15 * * * * *');

Issue: All of the above tasks are pretty time consuming & it seems from the results that these tasks are not running in parallel. And each tasks runs after the previous has ended.

Requirment How can i run them in parallel? I want all tasks to be executed (in parallel) as soon as the clock tick the specified time.

Laravel Version 5

like image 655
Knight Avatar asked Jul 20 '17 14:07

Knight


2 Answers

You can easily have multiple parallel commands running if you add runInBackground() to the chain. Like this:

$schedule->command('email:notifications1')
            ->cron('15 * * * * *')->runInBackground();
$schedule->command('email:notifications2')
            ->cron('15 * * * * *')->runInBackground();
$schedule->command('email:notifications3')
            ->cron('15 * * * * *')->runInBackground();

This creates a new process in the background so the Scheduler doesn't have to wait until the command executes. This doesn't even interfere with the withoutOverlapping() method because that works with mutex files.

Now you also have the benefit of having your commands in version control.

like image 188
Ogier Schelvis Avatar answered Oct 10 '22 01:10

Ogier Schelvis


The Laravel scheduler can only run one command at a time because of the limitations of PHP.

You could, however, add the cronjobs directly in your crontab file, this way, they will be executed in parallel in separate processes.

15 * * * * * php /path/to/artisan email:notifications1
15 * * * * * php /path/to/artisan email:notifications2
15 * * * * * php /path/to/artisan email:notifications3


Another way to fix this is to let the jobs start at another time. Because a new php process is started every minute by the cron job, these do not affect each other.

For example:

$schedule->command('email:notifications1')
            ->cron('5 * * * * *');
$schedule->command('email:notifications2')
            ->cron('10 * * * * *');
$schedule->command('email:notifications3')
            ->cron('15 * * * * *');
like image 39
Jerodev Avatar answered Oct 10 '22 03:10

Jerodev