nikoss
nikoss

Reputation: 61

Symfony2 - Check if command is running

Is there any way to check if a symfony command is already running? I have a command that runs without timeout and consuming data and i need to know if the command is already running.

Upvotes: 5

Views: 4586

Answers (2)

Nuryagdy Mustapayev
Nuryagdy Mustapayev

Reputation: 775

On later versions of Symfony you can use LockableTrait:

// ...
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Command\LockableTrait;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class UpdateContentsCommand extends Command
{
use LockableTrait;

// ...

protected function execute(InputInterface $input, OutputInterface $output): int
{
    if (!$this->lock()) {
        $output->writeln('The command is already running in another process.');

        return Command::SUCCESS;
    }

    // If you prefer to wait until the lock is released, use this:
    // $this->lock(null, true);

    // if not released explicitly, Symfony releases the lock
    // automatically when the execution of the command ends
    $this->release();

    return Command::SUCCESS;
}
}

Upvotes: 0

Stefan Gehrig
Stefan Gehrig

Reputation: 83622

You can use a lock to ensure that the command only runs once at a time. Symfony provides a LockHandler helper for that but you can easily do this with plain PHP as well.

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\LockHandler;

class WhateverCommand extends Command
{
    protected function configure() { }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $lock = new LockHandler('a_unique_id_for_your_command');
        if (!$lock->lock()) {
            $output->writeln('This command is already running in another process.');

            return 0;
        }

        // ... do some task

        $lock->release();
    }
}

Upvotes: 23

Related Questions