Laravel provides a convenient way to schedule tasks using its built-in Task Scheduling feature. Task scheduling allows you to execute Laravel Artisan commands periodically within your application. Let’s go through a practical example to see how to schedule tasks in Laravel:
Step 1: Define Your Task
For this example, let’s create a task that will delete all expired tokens from the database.
First, create a new Artisan command using the following command:
php artisan make:command ClearExpiredTokens
This command will generate a new file ClearExpiredTokens.php
in the app/Console/Commands
directory.
Open ClearExpiredTokens.php
and implement the logic to clear expired tokens:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\Token;
class ClearExpiredTokens extends Command
{
protected $signature = 'tokens:clear';
protected $description = 'Clear expired tokens';
public function handle()
{
Token::where('expiration_date', '<', now())->delete();
$this->info('Expired tokens cleared successfully.');
}
}
Step 2: Schedule the Task
Now, open the app/Console/Kernel.php
file and define your scheduled tasks in the schedule
method.
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected function schedule(Schedule $schedule)
{
$schedule->command('tokens:clear')->daily();
}
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
In this example, we scheduled the tokens:clear
command to run daily.
Step 3: Running the Scheduler
To run the scheduled tasks, you need to add the following Cron entry to your server.
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
This Cron entry will call the Laravel command scheduler every minute. The scheduler will then execute tasks as needed.
Step 4: Testing
To test if the scheduled task is working, you can manually run the scheduler using the following command:
php artisan schedule:run
This command will execute all the scheduled tasks defined in your Kernel
class.
That’s it! Now, your Laravel application will automatically clear expired tokens from the database on a daily basis.