LoginSignup
36
41

More than 5 years have passed since last update.

heroku schedulerの使い方 herokuで簡単な処理を定期的に自動的に実行する

Posted at

概要

以前書いた記事APIで複数通貨のレートを効率よく完全自動でデータベースに登録する方法! メンテナンスも簡単!で作成した、完全自動でレートを登録するコードをheroku上で1日に一回、自動的に実行したいと考えた。
railsで処理を定期的に実行する方法を調べてみると、cornなどのgemを使う方法も見つかったが、今回はherokuでの利用に限定されるが、最も簡単に実装できそうなheroku schedulerを使った実装を紹介する。

やり方は、以下の公式サイトを参考にした。
https://devcenter.heroku.com/articles/scheduler

事前準備

Heroku schedulerのadd-on自体は無料枠があり、無料で利用することができるが、アプリにadd-onを追加するためにはアカウントのverificationが必要であり、クレジットカードの登録が必要である。

やり方

1.実行したいタスクの作成

公式によるとrailsでは定期的に実行したい処理は、 lib/tasks/scheduler.rakeというファイルを作成して、そこに記述するのが一般的らしい。
公式に「これをコピーして書き替えろ」というコードのサンプルが載っているのでその通りにする。

サンプルコード

lib/tasks/scheduler.rake
desc "This task is called by the Heroku scheduler add-on"
task :update_feed => :environment do
  puts "Updating feed..."
  NewsFeed.update
  puts "done."
end

task :send_reminders => :environment do
  User.send_reminders
end

今回、私が作成したコード

lib/tasks/scheduler.rake
desc "This task is called by the Heroku scheduler add-on"
task :test_scheduler => :environment do
  puts "scheduler test"
  puts "it works."
end

task :update_rates => :environment do
  ENV["SSL_CERT_FILE"] = "app/controllers/cacert.pem"
    require 'open-uri'

    sources = ["USD","JPY","EUR","CNY", "KRW","THB", "VND", "SGD", "PHP"]
    currencies = sources.join(',')
    sources.each do |source|
        res = open('https://apilayer.net/api/live?access_key=アクセスキー&currencies=' + currencies + '&source=' + source + '&format=1')
        code, message = res.status # res.status => ["200", "OK"]
        if code == '200'
          result = ActiveSupport::JSON.decode res.read
          # resultを使ってなんやかんや処理をする
          @result = result['quotes'] #返ってきたjsonデータをrubyの配列に変換
          @result.each do |key, value|
            rate = Exchange.find_or_create_by(currency: key)
            rate.update(currency: key, rate: value)
          end
        else
          puts "Error!! #{code} #{message}"
        end
          puts @result
      end
end

rakeコマンドで実行できているかを確認するために文字列を出力する
test_schedulerというタスクも作った。

作成したら、コマンドラインラインから動作チェック

$rake test_scheduler

2. heroku schedulerのadd-onをアプリにインストール

herokuの自分のアカウントでheroku schedulerをインストールしたいアプリを開き、dashbordからconfigure Add-onsを開き、指示に従ってインストール。

3. jobの登録

dashbordのheroku schedulerをクリックしjobを登録し、時間などを設定する。

$rake test_scheduler

時間の設定はUTCで指定する点に注意。

これで終わり。

感想

Heroku schedulerの使い方を解説した記事はとても少なく、しかも、様々なgemを使用したやり方しか見つからなかった。
今回は公式サイトのやり方をそのまま行ったら、簡単に実装することができた。

36
41
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
36
41