1
3

More than 3 years have passed since last update.

【Rails】wheneverを用いたバッチ処理の実装

Last updated at Posted at 2020-04-26

目標

1分おきにメソッドを実行する。

開発環境

・Ruby: 2.5.7
・Rails: 5.2.4
・Vagrant: 2.2.7
・VirtualBox: 6.1
・OS: macOS Catalina

前提

下記実装済み。

ログイン機能実装
投稿機能実装

メソッドを定義

book.rb
class Book < ApplicationRecord
  def self.create_book
    Book.create(title: 'テスト', body: 'テスト')
  end
end

バッチ処理を実装

1.Gemを追加

Gemfile
gem 'whenever', require: false

require: false ➡︎ アプリケーションには反映させずに、ターミナルにのみ反映させる。

ターミナル
$ bundle

2.「schedule.rb」を作成

ターミナル
$ bundle exec wheneverize .

3.「schedule.rb」を編集

config/schedule.rb
env :PATH, ENV['PATH'] # 絶対パスから相対パス指定
set :output, 'log/cron.log' # ログの出力先ファイルを設定
set :environment, :development # 環境を設定

every 1.minute do # 1分毎に実行
  # 「Book」モデルの、「self.create_book」メソッドを実行
  runner 'Book.self.create_book'
end

4.「cron」を反映

ターミナル
$ bundle exec whenever --update-crontab

バッチ処理でよく使うコマンド

crontab -e ➡︎ cronをターミナル上で編集

$ bundle exec whenever ➡︎ cronの設定を確認

$ bundle exec whenever --update-crontab ➡︎ cronを反映

$ bundle exec whenever --clear-crontab ➡︎ cronを削除

1
3
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
1
3