LoginSignup
88
82

More than 5 years have passed since last update.

Herokuで単純なrubyスクリプトを定期的に実行する

Last updated at Posted at 2015-12-12

ActiveJobとか使わずに、単純なrubyスクリプトをHerokuで実行したい

前提条件

heroku toolbelt が導入されていること

準備

シンプルなrubyスクリプトを用意する

main.rb
p "hello"

git に commitする

git init
git add main.rb
git ci -m "First commit"

buildpacksを指定しながらherokuを開始

buildpacks って何?

  • 言語毎に実行環境が格納されたパッケージがある
  • Herokuのインスタンスにどのパッケージを使うか指定してあげる必要がある

buildpack-ruby を導入

heroku create --buildpack https://github.com/heroku/heroku-buildpack-ruby.git

Gemfileを用意

heroku-buildpack-ruby は Gemfile を読んで必要なgemをインストールするので、存在しないとデプロイ時にエラーを吐く

参考 → https://devcenter.heroku.com/articles/buildpacks#detection-failure

bundle init
# A sample Gemfile
source "https://rubygems.org"

ruby "2.2.3"
bundle install
git add Gemfile Gemfile.lock
git ci -m "Add Gemfile"

コードをherokuにデプロイ

git push heroku master

herokuでコードを実行

$ heroku run "ruby main.rb"
Running ruby main.rb on fathomless-temple-5052... up, run.9858
"hello"

実行できた!!

One-off Dynosについて

今回の heroku run のような一時的なコマンドや、管理者タスク等を実行する時に立ち上がるHerokuのインスタンス

お値段や制限は?

定期的に実行する

Heroku Schedulerを使う

  • Heroku Scheduler は、定期的に処理を実行してくれるcronみたいなことをしてくれるアドオン(freeなら無料)

p "hello" だと、出力が確認できないので、slack に出力するように実装を変える

main.rb
require "rubygems"
require "slack-notifier"

Slack::Notifier.new(ENV['WEBHOOK_URL']).ping("Hello World")
# A sample Gemfile
source "https://rubygems.org"

ruby "2.2.3"

gem "slack-notifier"

bundle install と、git push heroku master をすませておくこと

webhook url はリポジトリに入れたくないので、環境変数に持たせる

Heroku側に環境変数を渡す

heroku config:set WEBHOOK_URL="https://hooks.slack.com/services/********"

Heroku Schedulerの設定

アドオンの追加

heroku addons:create scheduler:standard

管理画面を開く

heroku addons:open scheduler

Heroku_Scheduler_-_Vimperator.png

管理画面から、10分に1回 ruby main.rb を実行するように設定

Heroku_Scheduler_-_Vimperator.png

しばらく待機...

Slack.png

出力された!!

今日はここまで

88
82
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
88
82