Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 - Check if command is running

Tags:

symfony

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.

like image 484
nikoss Avatar asked Dec 22 '15 08:12

nikoss


1 Answers

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();
    }
}
like image 197
Stefan Gehrig Avatar answered Oct 09 '22 14:10

Stefan Gehrig