How to schedule and run background tasks (jobs) using Laravel's Task Scheduler?

To schedule and run background tasks using Laravel's Task Scheduler, follow these steps:

  1. Create a new command: Run the following command in your terminal to generate a new command file:
php artisan make:command {command_name}

Replace {command_name} with the desired name for your command.

  1. Configure the command: Open the generated command file located in the app/Console/Commands directory. Update the signature property to define the command name and any arguments or options required. The handle method contains the logic that will be executed when the command is run.

  2. Register the command: Open the app/Console/Kernel.php file and add your command to the commands array. This will make it available for scheduling.

  3. Define the schedule: Open the app/Console/Kernel.php file and locate the schedule method. Inside this method, you can define the scheduled tasks using the ->command or ->exec methods.

  • ->command: Use this method to schedule your custom command. For example: $schedule->command('command:name')->daily();
  • ->exec: Use this method to schedule an arbitrary command or task. For example, to run a shell command: $schedule->exec('touch /path/to/file')->daily();
  1. Configure the frequency: Along with the ->command or ->exec methods, you can chain additional methods to define the frequency at which the task should run. Some common methods include daily(), hourly(), weekly(), monthly(), dailyAt('13:00'), etc.

  2. Queue the task (optional): If you want to queue a task to be executed asynchronously, you can call the ->queue method before specifying the schedule. For example:

$schedule->command('command:name')->daily()->queue();
  1. Save and test the schedule: Save the Kernel.php file and run the following command in your terminal to start the scheduler:
php artisan schedule:work

This command starts the Laravel scheduler, which will automatically run your scheduled tasks based on the defined schedule.

That's it! Your background tasks will now be scheduled and run automatically based on the specified frequency.