MENU

Heroku Schedulerで任意の間隔でスクリプトを実行したい

Heroku Schedulerで任意の間隔でスクリプトを実行したい

 1週間毎とかに実行したい。

Heroku Schedulerは実行間隔を10分毎、1時間毎、1日毎しか設定できない

 もう少し選べるといいが、仕方ない。。 f:id:spreadthec0ntents:20210417181113p:plain

1週間毎に起動させる例

 ただのブロック節でコントロールする。

全体像

  • 前回実行時間を記録するymlファイルを作る
  • ymlファイルをロードして現在時刻が前回実行時間から1週間後かを判定する
  • スクリプトの実行が終わったらその時間をymlに書き込む

前回実行時間を記録するymlファイルを作る

last_acted_at: '2021-04-01 08:27:20'

ymlファイルをロードして時刻を判定する

スクリプトの実行が終わったらその時間をymlに書き込む

class TimeKeeper
  require 'yaml'

  def last_acted_at
    data = open('./lib/time_keeper/last_acted_at.yml', 'r') { |f| YAML.load(f) }
    Time.zone.parse(data['last_acted_at'])
  end

  def update_last_acted_at
    data = { 'last_acted_at' => Time.current.strftime('%Y-%m-%d %H:%M:%S') }
    YAML.dump(data, File.open('./lib/time_keeper/last_acted_at.yml', 'w'))
  end

  def since_7days_from_last_acted_at?
    Time.current >= last_acted_at.since(7.days)
  end
end

スクリプトの例

@time_keeper = TimeKeeper.new
p '前回起動時から7日間が経過していません' and return unless @time_keeper.since_7days_from_last_acted_at?

〜実行したい処理〜

@time_keeper.update_last_acted_at

判定の時間を任意に変更すれば実行間隔を変えられる

 ただし10分未満毎とかはできないので注意。