Prevent to Run Artisan Command Multiple Times in Laravel 10

Prevent to Run Artisan Command Multiple Times in Laravel 10

Laravel's Artisan commands are a powerful tool that allows developers to interact with their applications through the command line. While Artisan commands make it easy to perform various tasks, there are instances where accidental multiple executions of a command can lead to undesired consequences or data inconsistencies. This tutorial shows how to prevent to run Artisan command multiple times in Laravel 10.

To enforce the restriction that only a single instance of a command can execute at any given time, just implement the Isolatable interface in the command class.

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Contracts\Console\Isolatable;

class TestCommand extends Command implements Isolatable
{
    protected $signature = 'app:test';

    public function handle(): int
    {
        sleep(5);
        $this->line('Long-running task done.');

        return Command::SUCCESS;
    }
}

If a command implements Isolatable, Laravel will automatically include an --isolated option for that command. When this option is used, Laravel will guarantee that there are no existing instances of the same command already running.

php artisan app:test --isolated

Laravel achieves this by trying to obtain an atomic lock using the default cache driver of the application. If there are other instances of the command in progress, the execution of the command will be prevented.

The [app:test] command is already running.

Leave a Comment

Cancel reply

Your email address will not be published.