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

问题描述:

我正在使用棘轮包创建聊天应用程序。 如何在Shared Hosting上运行命令“chat:serve”?我需要运行没有控制台线的命令。 我尝试这样做:Laravel:在后台运行自定义工匠命令

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主机”

解决此问题的某些选项可能会被共享主机阻止。从根本上来说,每个从你的web服务器调用一个php应用程序将启动一个php进程。当它完成时,过程返回。除非您希望此过程未完成,但您希望Web请求返回。所以你真的有三个选择:

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

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

3)您可以编写一个cron脚本来启动后台进程(如果没有运行的话)。与ssh命令类似,这使用其他内容来触发该过程。

我会注意到许多共享的webhosts不允许长时间运行的用户进程,因此可能不是这个项目的正确解决方案。