Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

JörgKünnemeyer's avatar

cron() method in scheduler: what happens with empty string or null?

Hi, I wrote a function that should only run at 13:00 on 1st and 3rd tuesday of a month (firstAndThirdWeekdayOfMonth(2, 13, 0)).

In this function I return a full crontab string if it should run ('0 13 * * 2'). If its not the correct day the cron should NOT run. Can I return an empty string or null to prevent the ->cron() function from being executed?

$schedule->command('ps:content_to_ps --full --default')->cron($this->firstAndThirdWeekdayOfMonth(2, 13, 0));

I don't want a conditional in the schedule() function of Kernel.php itself. I didn't find information on this anywhere. My AI claims null would work but who trusts AI?

Thanks for your feedback

0 likes
1 reply
LaryAI's avatar
Level 58

To address your question about using an empty string or null with the cron() method in Laravel's scheduler, it's important to understand how the cron() method interprets its argument.

The cron() method expects a valid cron expression. If you pass an empty string or null, it will not be a valid cron expression, and the scheduler will not know when to run the command. This could lead to unexpected behavior or errors.

A better approach would be to conditionally add the scheduled task only if the cron expression is valid. You can achieve this by using a conditional check before adding the task to the schedule. Here’s an example of how you can do this:

protected function schedule(Schedule $schedule)
{
    $cronExpression = $this->firstAndThirdWeekdayOfMonth(2, 13, 0);

    if ($cronExpression) {
        $schedule->command('ps:content_to_ps --full --default')->cron($cronExpression);
    }
}

private function firstAndThirdWeekdayOfMonth($weekday, $hour, $minute)
{
    // Your logic to determine if it's the 1st or 3rd Tuesday of the month
    // and return the appropriate cron expression or null/empty string if not

    // Example logic (you need to implement the actual logic):
    $isFirstOrThirdTuesday = true; // Replace with actual check

    if ($isFirstOrThirdTuesday) {
        return "{$minute} {$hour} * * {$weekday}";
    }

    return null; // or return an empty string
}

In this example, the firstAndThirdWeekdayOfMonth method returns a valid cron expression if it should run, otherwise it returns null. The schedule method then checks if the cron expression is valid before adding the command to the schedule.

This way, you avoid adding a task with an invalid cron expression and ensure that your command only gets scheduled when it should run.

Please or to participate in this conversation.