This is how I did it for an old version of Symfony - 2.0:
<?php
namespace Admin\MyBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Admin\MyBundle\Command;
/**
* @author Nataliya Naydenova
*
* @Route("/cron-manager")
*/
class CronManagerController extends Controller
{
/**
* Manually run cron jobs
*
* @param $commandName as defined in MyCommand.php
*/
private function runCommandMannually($commandName)
{
$text = 'Starting ...';
ini_set('max_execution_time', 600);
$command = new Command\MyCommand();
$command->setContainer($this->container);
$arguments = array(
'command' => 'my:command',
'name' => $commandName,
'--env' => 'local',
);
$input = new ArgvInput($arguments);
$output = new ConsoleOutput();
$returnCode = $command->run($input, $output);
if($returnCode == 0) {
$text .= 'successfully loaded!';
} else {
$text .= 'error!: ' . $returnCode;
}
$this->get('session')->setFlash('message', $text);
return $this->redirect($this->generateUrl('cron_manager'));
}
/**
* Pull first cron
*
* @Route("/product-image", name="cron_manager_product_image")
*/
public function productImageAction()
{
self::runCommandMannually('product_image_update');
}
/**
* Pull second cron
*
* @Route("/product-info", name="cron_manager_product_info")
*/
public function productInfoAction()
{
self::runCommandMannually('product_info_update');
}
}
Exlpanation
The commands I want to run via this controller are located in the Admin/MyBundle/Command/MyCommand.php class.
Because they take quite some time to execute I also increase the maximal execution time via ini_set('max_execution_time', 600);
The next thing to do is set the container for the MyCommand() object and then pass all necessary parameters to the input: the command itself, its name and the environment.
The $command->run()
method then runs and returns either 0 on success or a warning on failure. Depending on it I structure my flash message and redirect to the manager page from where I control those crons.