首页 > 解决方案 > Laravel 5.7 - 在一定时间后杀死工匠

问题描述

我正在开发一个laravel 5.7应用程序。

我创建了一个应该设置我的数据库的命令:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;

class TestSetupCommand extends Command
{
    protected $signature = 'test:data';

    protected $description = 'Basic Setup for Test Data';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        Artisan::call('migrate:refresh', ['--seed' => '']);
        Artisan::call('basis:cc');
        Artisan::call('tick:exchange');

        $this->info("DB freshly setup: DONE");
        $this->info("Coin: DONE");
        $this->info("Exchange Scrapped: DONE");
    }
}

我的问题是每个命令都需要几分钟才能运行完。用数据填充整个数据库总共花费了我 25 分钟。

我想每个命令只运行 1 分钟,然后杀死它们。

有什么建议可以在我的 laravel 命令中实现这一点吗?

标签: phplaravel

解决方案


我认为最好的方法是将这些命令提取到后台作业中。然后,此工匠命令将成为将该新作业(或多个作业)排队的代码。

为什么?通过覆盖如下值,很容易将作业配置为在 x 时间后超时

<?php

namespace App\Jobs;

class ProcessPodcast implements ShouldQueue
{
    /**
     * The number of seconds the job can run before timing out.
     *
     * @var int
     */
    public $timeout = 120;
}

另外,为什么要刷新数据库?这似乎是一个疯狂的想法,除非这纯粹是一个分析平台(根本没有用户数据)。如果该刷新命令超时,这可能是一件坏事 - 您可能会查看作业链接,以便保证刷新命令成功,然后其他命令(现在是新作业)已设置超时。


推荐阅读