Goal: By the end of this tutorial, you will learn how to manage tasks scheduling in Laravel, which allows you to automate tasks that run at specific intervals.
Learning Outcomes:
- Understand task scheduling in Laravel.
- Create tasks that run at specified intervals.
- Manage scheduled tasks.
Prerequisites:
- Basic knowledge of PHP and Laravel.
- Laravel environment set up on your local machine.
Laravel's task scheduling setup is done via the 'Console Kernel' class. This class has a method schedule
that is used to define your task schedule.
You can create a console command using the Artisan CLI tool by running the command php artisan make:command TestCommand
. This will create a new command class in the app/Console/Commands
directory.
To schedule a task, you can add a new call to the command
method within the schedule
method of your app/Console/Kernel.php
file.
php artisan make:command TestCommand
This will generate:
namespace App\Console\Commands;
use Illuminate\Console\Command;
class TestCommand extends Command
{
protected $signature = 'command:name';
protected $description = 'Command description';
public function handle()
{
//
}
}
$signature
is where you define the command name, and $description
is where you describe what the command does. The handle
method is where the logic of the command is defined.
Inside app/Console/Kernel.php
:
protected function schedule(Schedule $schedule)
{
$schedule->command('command:name')->hourly();
}
This command will run every hour.
In this tutorial, we learned how to create and schedule tasks in Laravel. You should now be able to automate tasks that run at specific intervals.
Next Steps:
- Try to schedule different types of tasks (daily, weekly, etc.).
- Learn more about task output and how to send output to email.
Additional Resources:
- Laravel Official Documentation
Exercise 1: Create a task that runs every day at noon.
Solution:
protected function schedule(Schedule $schedule)
{
$schedule->command('command:name')->dailyAt('12:00');
}
Exercise 2: Create a task that runs every Monday at 4:30 PM.
Solution:
protected function schedule(Schedule $schedule)
{
$schedule->command('command:name')->weeklyOn(1, '16:30');
}
Tips for Further Practice: Try to schedule tasks that send email notifications, write to logs or clean up old data.