Run a command third monday every month

Viewed 68

I have a artisan command that needs to be run the third monday of every month. I thought it should be easy with a simple cron rule saying "0 9 17-23 * 1", but now (a month after making the rule) I realize that my job has been run on EVERY monday of the month AND on EVERY day between the 17th and 23th. So obviously this doesn't work as I thought... After some googling it seems it's not easily solvable using only cron rules.

So, looking at the Laravel scheduling docs I think I have a solution, but I'm looking for verification I'm thinking right. If I instead do like this, will that do what I want? Don't want to try it the hard way again...

cron('0 9 17-23 * *')->mondays()
1 Answers

Unfortunately, the cron you are looking for can not be done without an external script of some sort.

In your case, I would leave the cronjob as it is, and create a larvel command, where you would check if the current day is a Monday in the given date-range or not.

This can be done with Carbon with the following function:

public function handle()
    {
        $todaysDay = Carbon::today()->dayOfWeek;

        // 1 is monday in Carbon.
        if($todaysDay == 1){
            $startDate = Carbon::parse(Carbon::now()->format('Y-m'))->addDays(17);
            $endDate = Carbon::parse(Carbon::now()->format('Y-m'))->addDays(23);

            // Check if todays date is in the given date-range
            if(Carbon::now()->between($startDate, $endDate)){

                // This is a monday between the 17nth and the 23rd
                // Do your magic stuff here.

            }
        }
    }

I'm sure that you could make this logic more effective, but this is a solution that solves your issue.

This command should then be ran by your cron :)

Related