Search code examples
phplaravelcronschedulingscheduler

Scheduling jobs every N minutes at different days


I have to run a cronjob in particular times:

First one: weekdays between 9:00 - 18:00 every 2 minutes

Second one: saturdays between 10:00 - 18:00 every 2 minutes

The farthest I could get is this:

$schedule->call(function () {
    (new SendSMS())->run();
})->weekdays()->between('9:00', '18:00');

I don't know how to add the everyTwoMinutes constraint since I only found these methods:

->everyMinute();    
->everyFiveMinutes();
->everyTenMinutes();
->everyThirtyMinutes();

And the second problem is that for the second condition I don't want to add another schedule like these:

$schedule->call(function () {
    (new SendSMS())->run();
})->saturdays()->between('11:00', '18:00');

I would to write a single one matching both times, is it possible?


Solution

  • Updated : This will run at the desired intervals.

        $schedule->call(function () {
            $datetime = date('Y-m-d H:i:s');
            echo $datetime;
        })->everyMinute()->when(function() {
    
            $now = new \DateTime();
    
            # don't run on Sundays
            if ($now->format('l') == 'Sunday') {
                return false;
            }
    
            # run every two minutes
            if ($now->format('i')%2 == 1) {
                return false;
            }
    
            if ($now->format('l') == 'Saturday') {
                $start_date = new \DateTime('today 10:00');
                $end_date = new \DateTime('today 18:00');
                return ($start_date <= $now && $now < $end_date);
            } else {
                $start_date = new \DateTime('today 09:00');
                $end_date = new \DateTime('today 18:00');
                return ($start_date <= $now && $now < $end_date);
            }
        });