Laravel作业调用Laravel命令

5

我有一个名为MyCommand的命令,我从一个名为MyJob的作业中调用它。当从作业中调用时,我无法看到命令输出。但是,如果我直接从命令行运行命令,则可以看到命令输出。

MyCommand.php代码:

namespace App\Console\Commands;

use Illuminate\Console\Command;

class MyCommand extends Command
{

    protected $signature = 'mycommand:doit';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $this->info('Process started');

        //Some process is done here

        $this->info('Process completed');
    }
} 

MyJob.php 代码:

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Artisan;

class MyJob implements ShouldQueue
{
    public function __construct()
    {

    }

    public function handle()
    {
        Artisan::call('mycommand:doit');
    }
} 
2个回答

4

理论上,当您运行作业时不在终端中(例如,可能排队或计划),则在终端外运行时输出不会被保存。

但是,您仍然可以通过Artisan::output()获取输出缓冲区。

示例:

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Artisan;

class MyJob implements ShouldQueue
{
    public function __construct()
    {

    }

    public function handle()
    {
        Artisan::call('mycommand:doit');
        $output = Artisan::output(); // $output is a string

        // Do whatever you want with $output
    }
}

更新:同步输出
您可以尝试以下命令: 命令示例:
class SlowCommand extends Command
{
    protected $signature = "slow";


    public function handle()
    {
        $max = 10;

        for ($i = 0; $i < $max; $i++) {
            $this->line($i);
            sleep(1);
        }
    }
}

// Synchronous output
Artisan::call("slow"); 
echo Artisan::output();

// Asynchronous output
$buffer = new ConsoleOutput();
Artisan::call("slow", [], $buffer);

这个方法是可行的,但它只会在命令完成时返回输出。我想要实时获取信息、通知和错误,而不是等整个命令完成后再获取。我已经找到了部分解决方案,不使用 $this->info,而是直接使用 echo 命令输出信息文本。 - Umut KIRGÖZ
当然可以,这是一段同步代码。但由于您没有明确您的Artisan调用范例,我没有尝试实时处理。 - Mathieu Bour
1
@UmutKIRGÖZ,我按照你的要求尝试包含异步输出。 - Mathieu Bour

0

使用Artisan::output方法通过Artisan门面获取上次执行命令的输出。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接