Skip to content

Instantly share code, notes, and snippets.

@trq
Created February 20, 2014 08:30
Show Gist options
  • Save trq/9109189 to your computer and use it in GitHub Desktop.
Save trq/9109189 to your computer and use it in GitHub Desktop.
Single Process Command
// src/Trq/FooBundle/Helper/SingleProcess.php
<?php
namespace Trq\FooBundle\Helper;
class SingleProcess
{
protected $callback;
protected $fp;
public function __construct($name, callable $callback)
{
$this->fp = fopen("/tmp/{$name}.lock", "w");
$this->callback = $callback;
}
public function __destruct()
{
fclose($this->fp);
}
protected function lockObtained()
{
return flock($this->fp, LOCK_EX | LOCK_NB);
}
protected function dropLock()
{
flock($this->fp, LOCK_UN);
}
public function process()
{
if ($this->lockObtained()) {
$result = call_user_func($this->callback);
$this->dropLock();
return $result;
} else {
throw new \RuntimeException('Unable to obtain the lock');
}
}
}
// src/Trq/FooBundle/Command/TestCommand.php
<?php
namespace Trq\FooBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Trq\FooBundle\Helper\SingleProcess;
class TestCommand extends ContainerAwareCommand
{
/**
* @see Command
*/
protected function configure()
{
$this->setName('trq:test');
}
/**
* @see Command
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
try {
(new SingleProcess('trq.test', function() use ($output) {
foreach (range(0, 10) as $i) {
$output->writeln('<fg=green>Hello World!</fg=green>');
sleep(1);
}
}))->process();
} catch (\RuntimeException $e) {
$output->writeln('<fg=red>' . $e->getMessage() . '</fg=red>');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment