php 39 lines · 7 steps

How task scheduling works in Laravel

Laravel's console Kernel registers recurring jobs with fluent frequency and safety constraints in one place.

Explained by highlit
1<?php
2 
3namespace App\Console;
4 
5use Illuminate\Console\Scheduling\Schedule;
6use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
7 
8class Kernel extends ConsoleKernel
9{
10 protected function schedule(Schedule $schedule): void
11 {
12 $schedule->command('sessions:gc')
13 ->hourly();
14 
15 $schedule->command('telescope:prune --hours=48')
16 ->daily();
17 
18 $schedule->command('cleanup:stale-records --days=30')
19 ->dailyAt('02:30')
20 ->timezone('America/New_York')
21 ->withoutOverlapping()
22 ->onOneServer()
23 ->runInBackground()
24 ->emailOutputOnFailure(config('mail.admin_address'))
25 ->appendOutputTo(storage_path('logs/cleanup.log'));
26 
27 $schedule->call(function () {
28 \App\Models\TemporaryUpload::where('created_at', '<', now()->subDay())
29 ->each(fn ($upload) => $upload->delete());
30 })->dailyAt('03:00')->name('prune-temp-uploads')->withoutOverlapping();
31 }
32 
33 protected function commands(): void
34 {
35 $this->load(__DIR__ . '/Commands');
36 
37 require base_path('routes/console.php');
38 }
39}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Defining all recurring work in one schedule method gives you a single source of truth instead of scattered crontab entries.
  2. 2Fluent constraints like withoutOverlapping and onOneServer make scheduled tasks safe to run across multiple servers.
  3. 3You can schedule existing Artisan commands or inline closures, whichever fits the job.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How task scheduling works in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code