繁体   English   中英

Laravel:在后台运行自定义工匠命令

[英]Laravel: Run Custom Artisan Command in Background

我正在使用Ratchet软件包进行聊天应用程序。 如何在共享主机上运行命令“ chat:serve”? 我需要在没有控制台行的情况下运行命令。 我尝试了这个:

Artisan::call('chat:serve');

或这个:

$serve = new WSChatServer();
$serve->fire();

但它不起作用。 网页永远不会停止加载。 我需要在后台运行此Artisan命令,并且该命令应一直运行。 我该怎么做? 没有VPS托管,是否可以这样做?

<?php namespace App\Console\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use App\Chat;

class WSChatServer extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'chat:serve';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Start chat server.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
            parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
            $port = intval($this->option('port'));
            $this->info("Starting chat web socket server on port " . $port);

            $server = IoServer::factory(
                new HttpServer(
                    new WsServer(
                        new Chat()
                    )
                ),
                $port
        );

        $server->run();
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [
        ];
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['port', 'p', InputOption::VALUE_OPTIONAL, 'Port where to launch the server.', 9090],
        ];
    }

}

您的问题暗示了您将最困难的地方:

“没有VPS托管是否可以做到这一点?”

您的共享主机可能会阻止某些解决此问题的选项。 从根本上来说,从您的网络服务器到php应用程序的每个调用都将启动php进程。 完成后,该过程返回。 除了您希望此过程未完成,但您希望Web请求返回。 因此,您确实有三个选择:

1)让php产生一个新的进程来运行您的artisan命令,然后返回原来的一个。 为此,您需要访问php中的流程扩展之一。 大多数共享主机默认情况下禁用此功能。 您还需要确保以关闭父进程时不会停止的方式创建进程。

2)您可以通过ssh登录并运行命令。 与之前相同,您需要确保生成该过程,以便在退出SSH连接时它不会停止。 Nohup在这里是一个有用的过程。

3)如果一个cron脚本未运行,则可以编写它来启动后台进程。 与ssh命令类似,它使用其他方法来触发该过程。

我要指出,许多共享的Web主机不允许长时间运行的用户进程,因此可能不是该项目的正确解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM