To schedule and run background tasks using Laravel's Task Scheduler, follow these steps:
php artisan make:command {command_name}
Replace {command_name}
with the desired name for your command.
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.
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.
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();
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.
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();
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.