Опрос Ajax с компонентом Symfony Process

Я запускаю долгосрочную задачу, которая возвращает инкрементный вывод о ходе выполнения задач с компонентом Symfony Process.

В одном из примеров показано, как получить вывод в реальном времени, а в другом примере показано, как запустить асинхронную задачу.

Я пытаюсь добиться того, чтобы передать результат getIncrementalOutput обратно в функцию опроса ajax, чтобы я мог обновлять интерфейс в реальном времени.

В любом случае кажется, что process-> start () блокируется, потому что мой вызов ajax возвращается через минуту, и к этому времени задача завершается.

Я думаю, что я пытаюсь избежать записи прогресса в БД или файл и получить вывод непосредственно из запущенной задачи PHP.

Не уверен, что это возможно.

3

Решение

Хотя я не совсем понимаю, что вы хотите создать, я написал нечто подобное, и, глядя на это, вы можете ответить на ваш вопрос:

Сначала я создал Команду, которая выполняет долгосрочную задачу:

class GenerateCardBarcodesCommand extends Command
{
protected function configure()
{
$this
->setName('app:generate-card-barcodes')
->setDescription('Generate the customer cards with barcodes')
->addArgument('id', InputArgument::REQUIRED, 'id of the Loy/Card entity')
;
}

protected function execute(InputInterface $input, OutputInterface $output)
{
$id = $input->getArgument('id');
// generate stuff and put them in the database
}
}

В контроллере процесс запущен и есть действие ajax

class CardController extends Controller
{
public function newAction(Request $request)
{
// run command in background to start generating barcodes
// NOTE: unset DYLD_LIBRARY_PATH is a fix for MacOSX develop using MAMP.
// @see http://stackoverflow.com/questions/19008960/phantomjs-on-mac-os-x-works-from-the-command-line-not-via-exec
$process = new Process(sprintf('unset DYLD_LIBRARY_PATH ; php ../../apps/spin/console spin:loy:generate-card-barcodes %d', $entity->getId()));
$process->start();

sleep(1); // wait for process to start

// check for errors and output them through flashbag
if (!$process->isRunning())
if (!$process->isSuccessful())
$this->get('session')->getFlashBag()->add('error', "Oops! The process fininished with an error:".$process->getErrorOutput());

// otherwise assume the process is still running. It's progress will be displayed on the card index
return $this->redirect($this->generateUrl('loy_card'));
}

public function ajaxCreateBarcodesAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $this->getEntity($id);
$count = (int)$em->getRepository('ExtendasSpinBundle:Loy\CustomerCard')->getCount($entity);
return new Response(floor($count / ($entity->getNoCards() / 100)));
}
}

// в шаблоне ветки извлекается ajax, который представляет собой просто число от 0 до 100, которое используется в индикаторе прогресса jquery ui.
{{‘Processing’ | trans}} …

            <script type="text/javascript">
$(function() {
function pollLatestResponse() {
$.get("{{ path('loy_card_ajax_generate_barcodes', {'id': entity[0].id}) }}").done(function (perc) {
if (perc == 100)
{
clearInterval(pollTimer);
$('#download-{{entity[0].id}}').show();
$('#progress-{{entity[0].id}}').hide();
}
else
{
$('#progress-{{entity[0].id}}').progressbar("value", parseInt(perc));
}
});
}

var pollTimer;
$(document).ready(function () {
$('#progress-{{entity[0].id}}').progressbar({"value": false});
pollTimer = setInterval(pollLatestResponse, 2000);
});
});
</script>
4

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]