LARAVEL

Laravel Scheduled Tasks & Cron Jobs

February 2, 2024 14 min read

Introduction

Laravel's Task Scheduler provides an elegant way to manage scheduled jobs within your application. Instead of setting up multiple cron entries, you can define all your scheduled tasks in one place using a clean, expressive syntax.

This guide covers everything you need to know about Laravel's built-in task scheduling system.

Scheduler Setup

To use Laravel's scheduler, you need to add a single cron entry that runs every minute:

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

For Laravel Forge or Vapor users, this can be configured through the dashboard.

Defining Scheduled Tasks

All scheduled tasks are defined in the schedule() method of your App\Console\Kernel class:

// app/Console/Kernel.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)
    {
        // Run a task every minute
        $schedule->call(function () {
            DB::table('recent_users')->delete();
        })->everyMinute();
        
        // Run a command daily
        $schedule->command('backup:run')->daily();
        
        // Run an artisan command
        $schedule->command('reports:generate')->dailyAt('08:00');
    }
}

Scheduling Syntax

Laravel provides many convenient methods for defining schedules:

// Time-based schedules
->everyMinute()           // Every minute
->everyFiveMinutes()      // Every 5 minutes
->hourly()               // Every hour
->daily()                // Once a day at midnight
->dailyAt('14:00')       // Once a day at 2 PM
->weekly()               // Once a week
->monthly()              // Once a month

// Conditional schedules
->weekdays()             // Only on weekdays
->sundays()              // Only on Sundays
->between('08:00', '18:00') // During specific hours
->when(function () {
    return $this->shouldRun();
})

Advanced Features

Preventing Task Overlap

// Prevent overlap using withoutOverlapping()
$schedule->command('backup:run')
    ->daily()
    ->withoutOverlapping();

Running Tasks in Background

// Run in background using runInBackground()
$schedule->command('heavy:process')
    ->daily()
    ->runInBackground();

Task Output

// Save output to file
$schedule->command('reports:generate')
    ->daily()
    ->appendOutputTo('/var/log/reports.log');

// Send output via email
$schedule->command('reports:generate')
    ->daily()
    ->sendOutputTo($filePath)
    ->emailOutputTo('admin@example.com');

Monitoring Tasks

Laravel provides built-in support for monitoring scheduled tasks:

// List all scheduled tasks
php artisan schedule:list

// Run scheduler locally (for testing)
php artisan schedule:test

// Force run scheduler in foreground
php artisan schedule:run --force

Summary

The Laravel Task Scheduler makes managing cron jobs simple and maintainable. By defining all your scheduled tasks in one place, you get better organization and easier maintenance.

For more Laravel tutorials, check out our guides on Laravel Queues and Laravel Horizon.