SDapkus
SDapkus

Reputation: 45

Laravel scheduler run task on first monday of month

I need to run command once a month on first Monday.

I had found one solution, but it does not work, this solution seems to be running every Monday and on first day of month. Tried looking into raw cronjob, so it seems that this is not possible to do with cronjob itself, and if Laravel scheduler is working on cronjob, then it is also not possible without some additional trigger mechanism.

$schedule->command('my:command')
        ->monthly()
        ->mondays()
        ->at('09:00');

Upvotes: 1

Views: 2398

Answers (2)

user2670486
user2670486

Reputation: 31

$schedule->command('foo')->mondays()->at("17:14")
            ->when(function () {
                return Carbon::parse('first monday of this month')->format("Y-m-d") == Carbon::now()->format('Y-m-d');
            });

Upvotes: 3

Martin Bean
Martin Bean

Reputation: 39389

You’ve answered your own question: Laravel’s task scheduling is based on cron jobs, and you can’t do “first Monday” as a raw cron expression; only days of the month.

So if you do need to run it on the first Monday of the month only, maybe scheduled the task for every Monday but then put a guard as the first line of your command’s handle method:

public function handle(): int
{
    if (! $this->isFirstMondayOfMonth()) {
        return 0;
    }

    // Rest of command

    return 0;
}

protected function isFirstMondayOfMonth(): bool
{
    $firstOfMonth = now()->firstOfMonth(1);
    $today = today();

    return $firstOfMonth->is($today);
}

Upvotes: 5

Related Questions