laravelscheduled-tasksphp-carbonlaravel-scheduler

does monthlyOn() works with between in laravel scheduler?


I have made a custom command and want it to run on month last day at 02:00 but I also want it to run after that between some period of time like 02:00 till 15:00 following is my scheduler

`$schedule->command('billing:generate')
                ->monthlyOn(Carbon::now()->endOfMonth()->subHours(5)->format("d"), "02:00");`

now what I think Ill do to achieve this is like this:

$schedule->command('billing:generate')
            ->monthlyOn(Carbon::now()->endOfMonth()->subHours(5)->format("d"), "02:00")
            ->between("02:00", "15:00");

will it work as I want? I am on laravel version 6.


Solution

  • As you are on Laravel 6, you can schedule your command to run every day, but just check is that day the last day of the month, something like this:

    // Runs exactly on "02:00" every month on its last day.
    // (Actually runs every day, but doesn't execute if the day is not the last day of the month).
    $schedule->command('billing:generate')->dailyAt('02:00')->when(function () {
        return Carbon::now()->endOfMonth()->isToday();
    });
    
    // Runs between "02:00" and "15:00" every month on its last day. 
    // (Actually runs every day, but doesn't execute if the day is not the last day of the month).
    $schedule->command('billing:generate')->daily()->between("02:00", "15:00")->when(function () {
        return Carbon::now()->endOfMonth()->isToday();
    });
    

    If you are on newer versions of Laravel you can use lastDayOfMonth to which you can provide a time, and if needed, you can also chain between on it.

    Also, to achieve what you want, you can specify 2 schedules and resolve the problem.

    It should be like this:

    // Runs exactly on "02:00" every month on its last day. 
    $schedule->command('billing:generate')->lastDayOfMonth("02:00");
    // Runs between "02:00" and "15:00" every month on its last day. 
    $schedule->command('billing:generate')->lastDayOfMonth()->between("02:00", "15:00");