2017年2月9日木曜日

Lumenでcron処理

どうも、俺です。

Lumen(多分5.3.1)でcronプログラムを作って登録する方法について。
おそらくLaravelはもうちょっと楽に出来そうですが、基本は同じはず。


Laravelの公式HP参照

【手順1】app/Console/Commands/以下にphpファイルを作成


$ vim app/Console/Commands/MyScript.php

内容は以下のような感じ。

<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;

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

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

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // ここに処理を書く
        echo "HELLO!\n";
    }
}


【手順2】app/Console/Kernel.phpに登録


$ vim app/console/Kernel.php

内容は以下。

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Laravel\Lumen\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        // ここに作成したコマンドクラスを追記していく。
        \App\Console\Commands\MyScript::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // ここに実行させたいコマンドクラスのシグネチャを記す。
        $schedule->command('my_script_signature')->cron('* * * * * *');
    }
}

【手順3】動作を試してみる


$ php artisan my_script_signature
HELLO!

問題なし!

【手順4】cronに登録する


* * * * * php /path/to/artisan schedule:run 1>> /path/to/cron.log 2>&1

これで定期的に処理をさせることが出来ます。



以上でぇぇぇぇす!

0 件のコメント: