首页 > 解决方案 > 在 Symfony 中运行一个独立的无休止的工作

问题描述


我有使用Ratchet的工作 websocket 服务器。websocket 本身工作正常。我可以使用 Symfony 的命令从终端运行它

php bin/console app:websocket:execute

我无法解决其中一些问题:

  1. 您需要专用一个终端来运行此命令
  2. 大多数虚拟主机服务不让您访问终端
  3. 我希望管理员能够打开和关闭 websocket 服务器
  4. 管理员不需要知道终端是什么

对于问题 1,我尝试使用这种“分离”作弊,但它不能解决问题 2:

php bin/console app:websocket:execute > /dev/null 2>&1 &

为了解决所有四个问题。我尝试过使用一个过程。但这种方法的问题是:

这是一个例子

$process = new Process("php bin/console");
$process->setWorkingDirectory(getcwd() . "/../");
$process->setTimeout(10);
$process->run(); // Stalls for 10 seconds, then throws timeout exception
$process-start(); // Doesn't stall, but terminates at end of request

// $process->run() ==== unreachable code
if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);
}

我尝试创建一个控制台应用程序,并从那里运行命令。但与流程相同的问题也适用于此处。

$application = new Application($this->kernel);
$application->setAutoExit(false);

$input = new ArrayInput(array(
    'command' => 'app:websocket:execute'
));

try {
    $ob = new BufferedOutput();
    $application->run($input, $ob);
    $output = $ob->fetch();
} catch (\Exception $e) {
    return null;
}

作为最后的手段,我尝试了一个名为DtcQueueBundle的包,因为它提到了以下内容:

使用方便

  • 用一两行代码启动后台任务
  • 轻松添加后台工作者服务
  • 只需几行即可将任何代码转换为后台任务

所以我按照他们的要求做了,创建了一个工作人员并尝试将其作为“后台任务”运行

use App\Ratchet\ForumUpdater;
use Ratchet\Http\HttpServer;
use Ratchet\Server\IoServer;
use Ratchet\WebSocket\WsServer;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class SocketWorker extends \Dtc\QueueBundle\Model\Worker
{
    public function execute()
    {
        $server = IoServer::factory(
            new HttpServer(
                new WsServer(
                    new ForumUpdater()
                )
            ),
            8080
        );

        $server->run();

        return "Websocket started";
    }

    public function getName()
    {
        return "websocket-server";
    }
}

他们的文档绝对是最差的!我什至试图深入研究他们的代码以从我的控制器内部开始工作。但我无法让它以一种超然的方式运行。

不管发生什么,我相信我的命令没有运行,因为它劫持了我的 PHP 线程。我想知道,有没有可能把这个没完没了的过程分开?甚至可以同时运行两个 PHP 实例吗?我会这么认为!

感谢您的帮助,对不起,很长的帖子

标签: phpbashsymfonywebsocketsymfony-process

解决方案


推荐阅读