LoginSignup
5
5

More than 3 years have passed since last update.

AWS Elastic Beanstalkで定期処理実行(cron)

Last updated at Posted at 2019-11-15

Heroku Schedulerでできたことを、Elastic Beanstalkでも行いたい

運用しているRailsアプリの本番環境を、HerokuからElastic Beanstalkに移行させました。
その際タスクの定期処理を行う方法で少し苦労したので、メモ的にシェアしておきます。

以前はHeroku Schedulerでrakeコマンドを呼び出せましたが、EBでそれを行うにはEC2内でcronを使うか、ワーカー環境でPOSTメソッドを呼び出す方法があるみたいです。今回は安く済ませたいので、前者を選びました。
後者の方法はこちらが参考になります。
https://qiita.com/tomoeine/items/38a9b2123e3afa1d5cd0

方法

このファイルを.ebextensionsに置くだけでOKです。あとはeb deployすれば、自動でcronのファイルを作成し自動実行してくれます。
eb sshで/etc/cron.dを確認してみてください。

.ebextensions/cron-sample.config
files: # filesは、EC2上にファイルを作成する。パスはアプリのルートではなくLinuxのルート。
    "/etc/cron.d/hello_world":
        mode: "000644"
        owner: root
        group: root
        content: |
            0 4 * * * root /usr/local/bin/hello_world.sh
       # 指定した頻度で、↓で作成するシェルスクリプトを実行。これは毎日午前4時

    "/usr/local/bin/hello_world.sh":
        mode: "000755"
        owner: root
        group: root
        content: |
            #!/bin/bash

            . /opt/elasticbeanstalk/support/envvars # アプリの環境変数読み込み
            cd /var/app/current

            /opt/rubies/ruby-2.5.7/bin/bundle exec /opt/rubies/ruby-2.5.7/bin/rake hello_world >> /var/log/hello_world.log 2>&1
            # rakeコマンド打つ。例ではhello_worldというrakeメソッドをすでに定義しているとする。
            # ログも出力。

            exit 0

commands:
    remove_old_cron:
        command: "rm -f /etc/cron.d/hello_world.bak" # バックアップを削除

参考

Linux サーバーでのソフトウェアのカスタマイズ
https://docs.aws.amazon.com/ja_jp/elasticbeanstalk/latest/dg/customize-containers-ec2.html#linux-files

Ruby on Railsの環境構築をElastic Beanstalkで行う
https://qiita.com/yuyasat/items/4d93b4ad4f86a6e13d50#cron%E3%81%A7rails-runner%E3%82%84rake%E3%82%BF%E3%82%B9%E3%82%AF%E3%82%92%E5%8B%95%E3%81%8B%E3%81%99

5
5
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
5
5