2
1

More than 3 years have passed since last update.

【Laravel】複数のartisanコマンドを同期実行し、エラーになったら途中で終了する

Posted at

環境

PHP : 5.6.30
Laravel : 5.1.46

実装

呼び出されるバッチの中身

Start.php
class Start extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'start';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'start batch';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        try {
            // 何らかの処理

            // 成功した場合、1を返す
            $ret = 1;

        } catch (Exception $e) {
            // エラーの場合、0を返す
            $ret = 0;
            Log::error("error_message: " . $e->getMessage());

        }

        return $ret;
    }
}

→他バッチも同様の戻り値を返すように設定

呼び出すバッチの中身

Batch.php
class Batch extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'batch';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Batch to be executed';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        try{

            $ret = $this->call('start');
            if($ret != 1){
                throw new Exception('start Error');
            }

            $ret = $this->call('end');
            if($ret != 1){
                throw new Exception('end Error');
            }

        } catch (Exception $e) {
            Log::debug("error_code : ". $e->getCode());
            Log::error("error_message : " . $e->getMessage());
        }
    }

}

補足

・戻り値を1と0としているのは、boolean型だとtrue/false問わず0で返ってきてしまったため。上手くいくならtrue/falseなどの判定で良いと思います。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1