中止和恢复Symfony控制台命令 [英] Aborting and resuming a Symfony Console command

查看:56
本文介绍了中止和恢复Symfony控制台命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Symfony控制台命令,该命令遍历潜在的大量项目并针对每个项目执行任务。由于集合可能很大,因此该命令可能需要很长时间才能运行(几小时)。命令完成后,它会显示一些统计信息。

I have a Symfony Console command that iterates over a potentially big collection of items and does a task with each of them. Since the collection can be big, the command can take a long time to run (hours). Once the command finishes, it displays some statistics.

我想以一种很好的方式中止命令。现在,如果我中止它(即在CLI中使用ctrl + c),则没有统计摘要,也没有办法输出恢复命令所需的参数。另一个问题是该命令可能会在处理项目的过程中终止–如果它只能在处理项目之间终止会更好。

I'd like to make it possible to abort the command in a nice way. Right now if I abort it (ie with ctrl+c in the CLI), there is no statistics summary and no way to output the parameters needed to resume the command. Another issue is that the command might be terminated in the middle of handling an item - it'd be better if it could only terminate in between handling items.

所以有一种告诉命令尽快中止的方法,还是将ctrl + c命令解释为这样?

So is there a way to tell a command to "abort nicely as soon as possible", or have the ctrl+c command be interpreted as such?

我尝试使用 ConsoleEvents :: TERMINATE 事件,尽管此处理程序仅在命令完成时触发,而在我按ctrl + c键时不会触发。而且我无法找到有关执行此类可恢复命令的更多信息。

I tried using the ConsoleEvents::TERMINATE event, though the handlers for this only get fired on command completion, not when I ctrl+c the thing. And I've not been able to find further info on making such resumable commands.

推荐答案

这对我有用。您需要在实际执行信号处理程序之前调用 pcntl_signal_dispatch 。没有它,所有任务将首先完成。

This is what worked for me. You need to call pcntl_signal_dispatch before the signal handlers are actually executed. Without it, all tasks will finish first.

<?php
use Symfony\Component\Console\Command\Command;

class YourCommand extends Command
{
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        pcntl_signal(SIGTERM, [$this, 'stopCommand']);
        pcntl_signal(SIGINT, [$this, 'stopCommand']);

        $this->shouldStop = false;

        foreach ( $this->tasks as $task )
        {
            pcntl_signal_dispatch();
            if ( $this->shouldStop ) break; 
            $task->execute();
        }

        $this->showSomeStats($output);
    }

    public function stopCommand()
    {
        $this->shouldStop = true;
    }
}

这篇关于中止和恢复Symfony控制台命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆