Navigation

Laravel

How to Run a Scheduled Task on a Single Server in Laravel

Learn how to run Laravel scheduled tasks on a single server using onOneServer() method. Prevent race conditions and duplicate work in multi-server environments.

Problem: You have a scheduled task, like generating a daily report, but your application runs on multiple servers. You need to ensure this task runs on only one server at a time to prevent duplicated work and race conditions.

Solution: Use the .onOneServer() method in your task definition within app/Console/Kernel.php.

// In app/Console/Kernel.php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('reports:generate')
                 ->daily()
                 ->onOneServer();
    }
}

How It Works

The .onOneServer() method is a simple yet powerful way to manage tasks in a load-balanced environment. It leverages your application's configured cache driver (e.g., Redis, Memcached) to set an atomic lock for the task.

When the scheduler runs on all your servers simultaneously, each server attempts to acquire a lock for the task. Only the first server to successfully acquire the lock will execute the command. All other servers will fail to get the lock and will skip running the task for that cycle.

Key Requirement: For this feature to work correctly, all servers in your environment must communicate with the same central cache server. This ensures that the lock is shared and respected across the entire application fleet.

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Laravel