Task Scheduling in Laravel allows developers to automate recurring tasks using the built-in scheduler, eliminating the need for a separate cron file. It simplifies scheduling operations like cleaning logs, sending reports, or syncing data.
The scheduler was introduced in Laravel to provide a programmatic interface for managing cron jobs, enabling developers to define all tasks within the application.
app/Console/Kernel.php
).Define a task to clean logs daily in app/Console/Kernel.php
:
protected function schedule(Schedule $schedule)
{
$schedule->command('logs:clear')->daily();
}
Then create the command:
php artisan make:command ClearLogs
In the generated command class:
namespace App\Console\Commands;
class ClearLogs extends Command
{
public function handle()
{
// Logic to clear logs
}
}
The scheduler runs this task daily when executed by a single cron entry: