In this post, we'll explore how you can schedule tasks in your Laravel applications using the built-in Laravel Scheduler. The Laravel Scheduler allows you to define commands or closures that should run at specified intervals, leveraging the power of cron jobs. Let's dive in with a simple example!
👉 Step 1: Define the Task
First, identify the task you want to schedule. It could be running a specific command, executing a closure, or triggering an artisan command. For this example, let's assume we have a SendEmails
command that we want to run every day at 8 AM.
👉 Step 2: Create the Laravel Command
Create the Laravel command using the following command:
php artisan make:command SendEmails
This will generate a SendEmails
command file in the app/Console/Commands
directory.
👉 Step 3: Define the Command Logic
Open the generated SendEmails
command file and define the logic for sending emails. For example:
use Illuminate\Console\Command;
class SendEmails extends Command
{
protected $signature = 'send:emails';
protected $description = 'Send daily emails';
public function handle()
{
// Your email sending logic here
$this->info('Emails sent successfully!');
}
}
👉 Step 4: Configure the Scheduler
Open the app/Console/Kernel.php
file and locate the schedule
method. Inside this method, you can define your scheduled tasks using the ->command
, ->exec
, or ->call
methods. In our example, we'll use the ->command
method:
use App\Console\Commands\SendEmails;
use Illuminate\Console\Scheduling\Schedule;
protected function schedule(Schedule $schedule)
{
$schedule->command(SendEmails::class)->dailyAt('08:00');
}
💡 In the above example, we use the ->command
method to schedule the SendEmails
command to run daily at 8 AM. You can adjust the schedule frequency and time as per your requirements.
👉 Step 5: Register the Scheduler in Cron
To enable Laravel's Scheduler, you need to add the following Cron entry to your server's task scheduler:
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
This Cron entry will execute the Laravel Scheduler every minute.
👉 Step 6: Run the Scheduler
To start the Laravel Scheduler, run the following command in your terminal:
php artisan schedule:run
This command will check your scheduled tasks and run them if they are due.