laravellaravel-scheduler

Laravel Scheduler: Should I use jobs or commands?


I'm torn on whether to schedule jobs or commands in the scheduler. I can't really find any in depth data on why I would choose one over the other. Typically, I've considered how long a given scheduled task will run and if it's "long" then I'll create a job, but I've recently switched a few jobs over to commands more recently because I can run them manually.

Also, if I'm using commands in the scheduler and I'm using runInBackground() how does that differ from a job?


Solution

  • When you use runInBackground, you're just sending the command to the shell background, like calling a command in the shell with & after the command.

    Jobs can be executed in queues, which can be retried, scaled, executed with middlewares, executed in batches and monitored with tools like Laravel Horizon.

    Tip: you can dispatch your jobs as commands by registering commands in routes/console.php that just dispatch the job, example:

    Artisan::command('my-job-command', fn () => dispatch(new MyJob()));

    The commands in this file are registered automatically by this code in the Kernel:

        protected function commands()
        {
            $this->load(__DIR__ . '/Commands');
    
            require base_path('routes/console.php');
        }