2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Yiiの拡張機能schedulingを使ってみた

Last updated at Posted at 2020-03-29

導入

  1. composer.jsonの require"omnilight/yii2-scheduling": "*" を追加

    composer.json
    "require": {
        ...,
        "omnilight/yii2-scheduling": "*"
    },
    
  2. composer update を実行

  3. console/configschedule.php を作成し、cronに設定する処理を記述

  4. 以下のcronを設定

    * * * * * php yiiコマンドが実行できるpath schedule/run --scheduleFile=schedule.phpがあるpath 1>> /dev/null 2>&1
    # 例) /var/www/html/app にyiiのプロジェクトがある場合
    php /var/www/html/app/yii schedule/run --scheduleFile=/var/www/html/app/console/config/schedule.php 1>> /dev/null 2>&1
    

schedule.phpでできること

時間指定

内容 関数 crontabでの意味 備考
毎分 everyMinute() * * * * *
N分おき everyNMinutes($minutes) */N * * * *
5分おき everyFiveMinutes() */5 * * * *
10分おき everyTenMinutes() */10 * * * *
30分ごと everyThirtyMinutes() 0,30 * * * *
毎時(0分実行) hourly() 0 * * * *
毎日(0時実行) daily() 0 0 * * *
毎月(1日実行) monthly() 0 0 1 * *
毎年(1/1実行) yearly() 0 0 1 1 *
1時と13時実行 twiceDaily() 0 1,13 * * *
時間指定 dailyAt('19:30') 30 19 * * * 引数は10:00,19:30などを渡す

曜日指定

内容 関数 crontabでの意味
月曜日 mondays() * * * * 1
火曜日 tuesdays() * * * * 2
水曜日 wednesdays() * * * * 3
木曜日 thursdays() * * * * 4
金曜日 fridays() * * * * 5
土曜日 saturdays() * * * * 6
日曜日 sundays() * * * * 0
月〜金 weekdays() * * * * 1-5
曜日と時間指定 weeklyOn(5, '17:30') 30 17 * * * 5

カスタム

内容 関数 crontabでの意味
カスタム cron('* * * * * *') * * * * *

例) schedule.php

schedule.php
$schedule->exec('ls')
->everyMinute()
->sendOutputTo(Yii::getAlias('@app')  . '/schedule.log')
->description('lsコマンドの実行');

$schedule->command('sample')
->everyMinute()
->sendOutputTo(Yii::getAlias('@app')  . '/sample.log')
->description('SampleControllerのactionIndexの実行');

$schedule->command('sample/view')
->everyMinute()
->sendOutputTo(Yii::getAlias('@app')  . '/sample-view.log')
->description('SampleControllerのactionViewの実行');

メリット

  • cron処理のgit管理ができる
  • cron変更時のオペレーションミスを減らせそう
    • crontab -ecrontab -rの打ち間違いなど

デメリット

  • cron処理の実行時間やタイミングの変更のたびにリリース作業が必要。
  • schedule.phpでやること/やらないことを決めておかないと複雑になりそう。

GitHubリポジトリ

omnilight/yii2-scheduling

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?