Awn Ali
Awn Ali

Reputation: 1379

Laravel 5.2: How to scheduled Command multiple times in a day

I am using laravel 5.2 commands via scheduler, i can call the command by following code:

$schedule->command('command:name')
                ->dailyAt('08:55');

but now i want to call above command daily at six different times i.e. 8:45, 9:15, 9:45,10:15 etc

$schedule->command('command:name')
            ->when(function(){return true;});

Above code, with when function, isn't working somehow, can someone suggest best practices of laravel.

Upvotes: 11

Views: 8863

Answers (3)

mukolweke
mukolweke

Reputation: 151

You can use the cron to setup custom time;

https://laravel.com/docs/8.x/scheduling#schedule-frequency-options

Example: 9am, 1pm and 5pm daily from Monday to Friday

foreach (['0 9 * * 1-5', '0 13 * * 1-5', '0 17 * * 1-5'] as $time) {
        $schedule->command('command:name')->cron($time);
    }

you can use https://crontab.guru to get the custom times accurately.

Upvotes: 0

cartbeforehorse
cartbeforehorse

Reputation: 3467

For Laravel 5.5 there's the between() function. It's documented here

$schedule ->command('foo')
          ->everyThirtyMinutes()
          ->between('8:45', '10:15');

Granted that won't do you for Laravel 5.2, but I'm sure you could do something with the when() function, as that is also documented for v5.2

$schedule ->command('foo')
          ->everyThirtyMinutes()
          ->when(function () {
              return date('H') >= 8 && date('H') <= 11;
          });

Upvotes: 8

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

Why not just define 4 tasks, it's simple and readable:

$schedule->command('command:name')->dailyAt('08:55');
$schedule->command('command:name')->dailyAt('09:15');
$schedule->command('command:name')->dailyAt('09:45');
$schedule->command('command:name')->dailyAt('10:15');

Also, you can put it in a loop:

foreach (['08:45', '09:15', '09:45', '10:15'] as $time) {
    $schedule->command('command:name')->dailyAt($time);
}

Upvotes: 29

Related Questions