Menü schliessen
Created: February 13th 2025
Last updated: February 14th 2025
Categories: Common Web Development,  IT Development,  Laravel,  Php
Author: Tim Fürer

Laravel: How to Schedule Tasks / Set Up Cron Jobs

Tags:  cron jobs,  guide,  Laravel,  PHP
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Laravel offers a convenient solution for scheduling tasks (setting up Cron jobs) within your application's code. This saves you the hassle of managing a (potentially massive) Cron configuration file on your server.


PREREQUISITES

Artisan runs all due scheduled tasks when the command "schedule:run" is executed. So, for Laravel to be able to do its magic, we have to register a single Cron job on our server: one that executes the Artisan "schedule:run" command every other minute.

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

If you're using Laravel Sail, use the following configuration instead:

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

Adding Jobs (routes/console.php)

One place to define your job schedule at is the "routes/console.php" file. Here are some example entries:

Using closure:

<?php

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schedule;

Schedule::call(function () {
    DB::table('recent_users')->delete();
})->daily();

Using invokable object:

<?php

use Illuminate\Support\Facades\Schedule;

Schedule::call(new DeleteRecentUsers)->daily();

Using command:

<?php

use Illuminate\Support\Facades\Schedule;

Schedule::command('emails:send Taylor --force')->daily();

Using command class:

<?php

use Illuminate\Support\Facades\Schedule;

Schedule::command(SendEmailsCommand::class, ['Taylor', '--force'])->daily();

Adding Jobs (bootstrap/app.php)

Another place to define jobs at is is the "bootstrap/app.php" file. This is where your Laravel application instance is set up and created. During that set up process, which is done through a series of chained method calls, you have the chance to define a job schedule. The relevant chain method is "->withSchedule()". It's provided with an instance of the scheduler in its first argument/parameter. Here's an example:

<?php

use Illuminate\Console\Scheduling\Schedule;

->withSchedule(function (Schedule $schedule) {
    $schedule->call(new DeleteRecentUsers)->daily();
})

Timing Options

All of the examples were scheduled using a "->daily()" frequency. Here are some other Schedule Frequency Options that Laravel supports.


Viewing Complete Schedule

Once you've finalised your schedule, you may want an overview over all your tasks. The "schedule:list" Artisan command is here to satisfy this desire.

php artisan schedule:list

Or for Sail users:

vendor/bin/sail artisan schedule:list