Automated Task Scheduling
Laravel's scheduler lets you define scheduled tasks in PHP code instead of managing cron entries.
Defining Scheduled Tasks
// routes/console.php
use Illuminate\Support\Facades\Schedule;
Schedule::command('newsletter:send')->weeklyOn(1, '8:00');
Schedule::command('sitemap:generate')->daily();
Schedule::command('telescope:prune')->daily();
Schedule::command('queue:prune-failed --hours=48')->daily();
// Custom closure
Schedule::call(function () {
DB::table('sessions')->where('last_activity', '<', now()->subHours(24))->delete();
})->dailyAt('03:00');
// Conditional scheduling
Schedule::command('reports:generate')
->monthlyOn(1, '09:00')
->environments(['production'])
->emailOutputOnFailure('admin@example.com');
Schedule Frequencies
->everyMinute()
->everyFiveMinutes()
->hourly()
->daily()
->dailyAt('13:00')
->weekly()
->weeklyOn(1, '8:00') // Monday at 8 AM
->monthly()
->monthlyOn(1, '09:00')
->quarterly()
->yearly()
->cron('0 */6 * * *') // Custom cron expression
Preventing Overlaps
Schedule::command('reports:generate')
->daily()
->withoutOverlapping()
->runInBackground();
Server Setup
Add one cron entry to your server:
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
Laravel checks every minute and runs any tasks that are due. One cron entry handles all your scheduled tasks.
Testing Schedules
php artisan schedule:list # View all scheduled tasks
php artisan schedule:test # Run a specific task interactively
php artisan schedule:run # Execute due tasks now
The scheduler eliminates fragile server cron management and keeps your scheduling logic version-controlled alongside your code.