Tutorials  /  Linux Basics

Automate Laravel Cron Jobs and Task Scheduling

Ccentron Redaktion · October 2025 ·11 min read ·Linux Basics, Tutorial

Laravel provides a built-in task scheduling feature that simplifies automating recurring processes. Using Laravel cron jobs, you can schedule and manage tasks directly within your Laravel application, instead of adding entries manually to the system crontab. The Laravel scheduler supports flexible intervals, timezone management, and output handling, making it ideal for automating database cleanups, generating reports, or sending email notifications.

This guide explains how to configure Laravel cron jobs. You will learn how to set up the Laravel task scheduler, create custom Artisan commands, and automate scheduled jobs in your Laravel project.

Prerequisites

Before proceeding, ensure the following requirements are met:

  • You have access to a running instance such as Ubuntu 24.04 with an active Laravel project.
  • You are logged in as a non-root user with sudo privileges.
VM

Matching infrastructure at centron

No hardware needed to follow along: ccloud³ VMs with full root access start at €3.12 per month, billed by the hour and ready in seconds. Rent a cloud server →

Schedule Tasks in Laravel

Scheduled tasks in Laravel are automated operations that run at predefined intervals. These tasks can include Artisan commands or any function that you define to execute automatically within your Laravel application. Follow the steps below to create and verify a new scheduled task.

Step 1: Navigate to Your Laravel Project Directory

Console
$ cd /var/www/laravelapp

Step 2: Verify Directory Ownership

Console
$ ls -l

Expected output:

Code
drwxr-xr-x  6 www-data www-data   4096 Apr 23 20:57 app/
-rwxr-xr-x  1 www-data www-data    425 Apr 23 20:57 artisan*
drwxr-xr-x  3 www-data www-data   4096 Apr 23 20:57 bootstrap/
-rw-r--r--  1 www-data www-data   2419 Apr 23 20:57 composer.json
-rw-r--r--  1 www-data www-data 297315 Apr 23 20:57 composer.lock
drwxr-xr-x  2 www-data www-data   4096 Apr 23 20:57 config/
...

The www-data group owns the /var/www/laravelapp directory, allowing users in the group to access Laravel project files.

Step 3: Verify the Current User

Console
$ whoami

Expected output:

Code
linuxuser

Step 4: Add the User to the www-data Group

Replace linuxuser with your actual username to grant access to the Laravel directory.

Console
$ sudo usermod -a -G linuxuser www-data

Step 5: Grant Ownership of the Directory

Console
$ sudo chown -R linuxuser:www-data /var/www/laravelapp

Step 6: Verify the Current Working Directory

Console
$ pwd

Output:

Code
/var/www/laravelapp

Step 7: Backup and Edit console.php

Console
$ mv routes/console.php routes/console.php.ORIG

Create a new routes/console.php file:

Console
$ nano routes/console.php

Step 8: Define a Scheduled Task

Code
<!--?php use Illuminate\Support\Facades\Schedule; Schedule::call(function () { \Log::info('This is a scheduled task running at: ' . now()); return 0; })--->everySecond();
?>

This configuration logs the current timestamp to the Laravel log file every second.

Step 9: Run the Laravel Scheduler

Console
$ php artisan schedule:run

Expected output:

Code
2025-04-14 20:44:07 Running [Callback] ......................... 7.64ms DONE
2025-04-14 20:44:08 Running [Callback] ......................... 0.32ms DONE
2025-04-14 20:44:09 Running [Callback] ......................... 0.34ms DONE
2025-04-14 20:44:10 Running [Callback] ......................... 0.35ms DONE

The scheduled task is now active and running as expected. Press Ctrl + C to stop it.

Create Reusable Laravel Commands

Artisan commands in Laravel allow developers to create reusable CLI operations for automating repetitive or complex tasks. These commands can be executed manually or scheduled automatically. Follow these steps to build and test a custom Artisan command.

Step 1: Create the CacheClearCommand

Console
$ php artisan make:command CacheClearCommand

This creates a new command file inside the app/Console/Commands/ directory.

Step 2: Edit the Generated File

Console
$ nano app/Console/Commands/CacheClearCommand.php

Step 3: Add the Command Logic

Code
<!--?php namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\Artisan; class CacheClearCommand extends Command { protected $signature = 'app:clear-cache'; protected $description = 'Clear the application cache'; public function handle() { $this--->info('Clearing application cache...');
        $exitCode = Artisan::call('cache:clear');

        if ($exitCode === 0) {
            $this->info('Application cache cleared successfully!');
            \Log::info('Application cache cleared at ' . now());
        } else {
            $this->error('Failed to clear application cache.');
            \Log::error('Failed to clear application cache at ' . now());
        }

        return Command::SUCCESS;
    }
}
?>

This code defines a custom command named app:clear-cache, which clears the application cache and logs the process in storage/logs/laravel.log.

Step 4: Test the Custom Command

Console
$ php artisan app:clear-cache

Expected output:

Code
Clearing application cache...
Application cache cleared successfully!

This confirms that the custom Artisan command is working properly.

Configure Laravel Cron Jobs to Schedule Commands

The Laravel task scheduling system allows you to automate command executions at defined intervals using a simple and expressive syntax. Follow the steps below to schedule the app:clear-cache command you created earlier to run every two seconds.

Step 1: Back Up the routes/console.php File

Console
$ mv routes/console.php routes/console.php.bak

Step 2: Create the routes/console.php File

Console
$ nano routes/console.php

Step 3: Add the Scheduling Code

Code
<!--?php use Illuminate\Support\Facades\Schedule; Schedule::command('app:clear-cache')--->everyTwoSeconds();
?>

The above code schedules the app:clear-cache command to run every two seconds. Keep in mind that the task will only execute when the schedule:run command is triggered.

Supported Laravel Schedule Frequency Options

Laravel offers multiple methods to define how frequently tasks run. Below are commonly used scheduling options that can be added to the routes/console.php file.

Monthly

Code
Schedule::command('app:clear-cache')->monthly();

Runs the app:clear-cache command once a month.

Daily at a Specific Time

Code
Schedule::command('app:clear-cache')->dailyAt('08:00');

Executes the command every day at 8:00 AM.

Daily

Code
Schedule::command('app:clear-cache')->daily();

Runs the command once every day at midnight.

Weekly on a Specific Day and Time

Code
Schedule::command('app:clear-cache')->weeklyOn(1, '8:00');

Executes the task every Monday at 8:00 AM.

Every Hour

Code
Schedule::command('app:clear-cache')->hourly();

Runs the command once per hour.

Every Five Minutes

Code
Schedule::command('app:clear-cache')->everyFiveMinutes();

Runs the command every five minutes.

Every Minute

Code
Schedule::command('app:clear-cache')->everyMinute();

Executes the command once every minute.

Using a Custom Cron Expression

Code
Schedule::command('app:clear-cache')->cron('*/5 * * * 1-5');

Runs the task every five minutes from Monday through Friday.

Log the Output to a File

Code
Schedule::command('app:clear-cache')
    ->daily()
    ->appendOutputTo(storage_path('logs/cleanup.log'));

Appends task output to a log file after execution.

Email Task Output

Code
Schedule::command('app:clear-cache')
    ->daily()
    ->emailOutputTo('admin@example.com');

Sends the task’s output to the specified email address.

Email Only on Failure

Code
Schedule::command('app:clear-cache')
    ->daily()
    ->emailOutputOnFailure('admin@example.com');

Sends an email notification only if the task fails.

Advanced Scheduling Methods

Laravel provides advanced scheduling methods to enhance how tasks are executed. These allow developers to fine-tune the timing, execution rules, and handling of scheduled jobs.

Prevent Overlapping Tasks

Code
Schedule::command('app:clear-cache')->daily()->withoutOverlapping();

Prevents a new instance of a task from starting if the previous one is still running.

Run on One Server Only

Code
Schedule::command('app:clear-cache')->daily()->onOneServer();

Ensures the task runs on only one server in multi-server environments.

Run in the Background

Code
Schedule::command('app:clear-cache')->daily()->runInBackground();

Executes tasks in the background, avoiding process blocking.

Run During Maintenance Mode

Code
Schedule::command('app:clear-cache')->daily()->evenInMaintenanceMode();

Ensures the task runs even when Laravel is in maintenance mode.

Conditional Task Execution

Code
Schedule::command('app:clear-cache')
    ->daily()
    ->when(function () {
        return \App\Models\User::count() > 100;
    });

Executes the task only when a specific condition is met, such as having more than 100 users.

Specify Time Ranges for Execution

Code
Schedule::command('app:clear-cache')
    ->hourly()
    ->between('8:00', '17:00');

Ensures tasks run only between 8:00 AM and 5:00 PM.

Handle Success and Failure Events

Code
Schedule::command('app:clear-cache')
    ->daily()
    ->onSuccess(function () {
        \Log::info('Cache cleared successfully');
    })
    ->onFailure(function () {
        \Notification::route('mail', 'admin@example.com')
            ->notify(new \App\Notifications\TaskFailed('Cache Clear'));
    });

Defines custom actions based on task outcomes using onSuccess() and onFailure().

Automate Laravel Cron Jobs with Cron

You can automate Laravel cron jobs using the system cron service by adding a new entry that triggers the Laravel scheduler. Follow the steps below to configure and automate Laravel cron jobs through the crontab file.

Step 1: Open the Crontab Editor

Console
$ crontab -e

When prompted, select your preferred text editor, such as nano.

Step 2: Add the Laravel Scheduler Entry

Add the following line to run the Laravel scheduler every minute.

Code
* * * * * cd /var/www/laravelapp && php artisan schedule:run >> /dev/null 2>&1

This cron job runs the Laravel scheduler every minute inside the project directory. The php artisan schedule:run command executes the Laravel task scheduler, while the output is redirected to /dev/null to ensure silent operation.

Step 3: Verify the Cron Job

List all active cron jobs for your user account to confirm that the Laravel cron entry has been added.

Console
$ crontab -l

Expected output:

Console
# m h  dom mon dow   command
* * * * * cd /var/www/laravelapp && php artisan schedule:run >> /dev/null 2>&1

Test and Validate Laravel Cron Jobs

Follow these steps to ensure your Laravel scheduler and automated cron tasks are functioning correctly.

Step 1: Verify the Current Directory

Console
$ pwd

Output:

Code
/var/www/laravelapp

Step 2: List Scheduled Tasks

Console
$ php artisan schedule:list

Expected output:

Code
* * * * *  php artisan app:clear-cache ....................................................................... Has Mutex › Next Due: 58 seconds from now

This confirms the scheduled command, its timing, and the current execution status.

Step 3: Monitor the Laravel Log File

Monitor the log file to verify that the scheduled tasks are executing correctly.

Console
$ tail -f /var/www/laravelapp/storage/logs/laravel.log

Expected output if the cron job is active:

Code
[2025-04-14 20:14:00] local.INFO: Application cache cleared at 2025-04-14 20:14:00  
[2025-04-14 20:15:00] local.INFO: Application cache cleared at 2025-04-14 20:15:00  
[2025-04-14 20:16:00] local.INFO: Application cache cleared at 2025-04-14 20:16:00  
......................

The timestamps confirm that the Laravel scheduler is executing as intended. Press Ctrl + C to stop monitoring the log file.

Conclusion

You have successfully configured Laravel cron jobs using the built-in scheduler and automated their execution via system cron. With this setup, recurring tasks such as cache clearing or data cleanup can run efficiently at specified intervals. For further details and advanced scheduling techniques, consult the official Laravel documentation.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Linux Basics
Teilen
Noch offene Fragen?

Unser Team hilft Ihnen bei Ihrem konkreten Setup weiter – von Menschen, die die Plattform selbst betreiben.

War dieses Tutorial hilfreich?

Ihre Antwort wird anonym gespeichert und hilft uns, die Tutorials zu verbessern.

Kommentare

Noch keine Kommentare – stellen Sie die erste Frage zu diesem Tutorial.

Zum Kommentieren anmelden

Kommentare stehen centron-Kunden offen. Melden Sie sich in Ihrem Konto an, um eine Frage zu diesem Tutorial zu stellen.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren