Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scheduling a task twice a day with Laravel

Tags:

cron

laravel

I'm trying to schedule a command twice a day:

Here is my code:

protected function schedule(Schedule $schedule)
    {

        $morningCarbonHour = Carbon::now();
        $morningCarbonHour->hour = 23;
        $morningCarbonHour->minute = 27;
        $morningCarbonHour->second = 00;

        $hourIni = $morningCarbonHour->format('H:i');

        $nightCarbonHour = Carbon::now();
        $nightCarbonHour->hour = 23;
        $nightCarbonHour->minute = 28;
        $nightCarbonHour->second = 00;

        $hourFin = $nightCarbonHour->format('H:i');

        $schedule->command('check:time')
                 ->twiceDaily($hourIni,$hourFin)
                 ->timezone('America/Mexico_City');
    }

I get this error message:

[2016-05-31 23:29:01] production.ERROR: exception 'InvalidArgumentException' with message 'Invalid CRON field value 23:27,23:28 at position 1' in /home/forge/myproject/vendor/mtdowling/cron-expression/src/Cron/CronExpression.php:147

Stack trace:

I don't really know why??? Any Idea???

like image 270
Juliatzin Avatar asked Jun 01 '16 04:06

Juliatzin


1 Answers

twiceDaily accepts parameters as hours.
Default values is public function twiceDaily($first = 1, $second = 13) which means task will be execute daily at 1:00 & 13:00.

You are trying to run task 23:27 and 23:28 which is technically not available using this (twiceDaily) method, because it does not accepts minutes as parameter.


Solution

Change twiceDaily() to <command>->cron('27,28 23 * * *');.
It will run Your command at 23:27 and 23:28.


Or if You want to run command two times a day, with a different hour and minutes, You should use two separated commands with dailyAt() (two dailyAt() on one command, will override and will not work as You want).

like image 122
Giedrius Kiršys Avatar answered Nov 08 '22 23:11

Giedrius Kiršys