How to Configure Laravel Cron Jobs and Task Scheduling

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.

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

Step 2: Verify Directory Ownership

Expected output:

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

Expected output:

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

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

$ sudo usermod -a -G linuxuser www-data

Step 5: Grant Ownership of the Directory

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

Step 6: Verify the Current Working Directory

Output:

Step 7: Backup and Edit console.php

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

Create a new routes/console.php file:

Step 8: Define a Scheduled Task

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

Step 9: Run the Laravel Scheduler

$ php artisan schedule:run

Expected output:

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

$ php artisan make:command CacheClearCommand

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

Step 2: Edit the Generated File

$ nano app/Console/Commands/CacheClearCommand.php

Step 3: Add the Command Logic

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

$ php artisan app:clear-cache

Expected output:

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

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

Step 2: Create the routes/console.php File

Step 3: Add the Scheduling Code

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

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

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

Daily at a Specific Time

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

Executes the command every day at 8:00 AM.

Daily

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

Runs the command once every day at midnight.

Weekly on a Specific Day and Time

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

Executes the task every Monday at 8:00 AM.

Every Hour

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

Runs the command once per hour.

Every Five Minutes

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

Runs the command every five minutes.

Every Minute

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

Executes the command once every minute.

Using a Custom Cron Expression

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

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

Appends task output to a log file after execution.

Email Task Output

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

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

Email Only on Failure

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

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

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

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

Run in the Background

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

Executes tasks in the background, avoiding process blocking.

Run During Maintenance Mode

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

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

Conditional Task Execution

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

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

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

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.

* * * * * 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.

Expected output:

# 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

Output:

Step 2: List Scheduled Tasks

$ php artisan schedule:list

Expected output:

* * * * *  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.

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

Expected output if the cron job is active:

[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.

Source: vultr.com

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in: