How to Schedule Tasks in Laravel

How to Schedule Tasks in Laravel

How to Schedule Tasks in Laravel

Define all scheduled tasks in routes/console.php and manage them with a single server cron entry.

Step 1 — Add the Server Cron Entry

Add this single line to your server's crontab — Laravel handles the rest:

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

Step 2 — Define Scheduled Tasks

// routes/console.php
use Illuminate\Support\Facades\Schedule;

// Run an Artisan command every day at midnight
Schedule::command('reports:generate')->daily();

// Run every hour between 8am and 5pm on weekdays
Schedule::command('emails:digest')
    ->hourly()
    ->weekdays()
    ->between('8:00', '17:00');

// Run a closure every 5 minutes
Schedule::call(function () {
    DB::table('temp_tokens')->where('expires_at', '<', now())->delete();
})->everyFiveMinutes();

// Run a shell command weekly
Schedule::exec('node /scripts/rebuild-index.js')->weekly();

Step 3 — Prevent Overlapping

Schedule::command('reports:generate')
    ->daily()
    ->withoutOverlapping(); // skips if previous run is still going

Step 4 — Test Locally

php artisan schedule:list   # view all scheduled tasks
php artisan schedule:run    # run tasks due right now
php artisan schedule:work   # run scheduler every minute (for local dev)
All Comments