Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Laravel 11 - Prevent Scheduling Slowing Artisan/Composer Commands

Laravel 11 has changed the way to perform scheduling, so that you simply place lines like the following directly inside app/console.php

Schedule::job(new MyJobName)->dailyAt('03:00');

However, what the documentation doesn't mention, is that this console.php file is included/required whenever any artisan commands are run. If you don't believe me, then just try putting a die('got here') message in the file, and see what happens when you run php artisan help.

Also, you may know that artisan commands are often placed inside the composer.json for performing actions like so:

    "scripts": {
        "post-autoload-dump": [
            "@php artisan package:discover --ansi"

Why do I mention this? Well if you are like me and your Laravel application has some complicated logic that runs to determine what jobs to schedule, then this massively slows down running composer update, composer install, or executing literally any artisan command.

Luckily this was easily resolved by simply adding the following function to the app/console.php file, which will check if we are running from having called php artisan schedule:run:

function isRunningScheduleRunCommand() : bool
    return App::runningInConsole() && App::runningConsoleCommand('schedule:run');

Then simply place that around your calls to Schedule:: like so:

if (isRunningScheduleRunCommand())
    Schedule::job(new MyJobName)->dailyAt('03:00');

Now your scheduling logic will only run when scheduler is running.

Last updated: 26th March 2024
First published: 26th March 2024