I tried to use whenever
which executes Rails regularly, but I decided to do it with docker because it was difficult to manage environment variables and permissions when implementing it directly on Mac.
The execution environment is as follows ・ Ruby 2.6.3 ・ Rails 5.2.4 · MySQL 8.0.19
Dockfile
, docker-compose.yml
looks like this
It's not much different from normal docker settings, but since we use whenever, we've added the settings for installing corn
and running cron in the foreground.
FROM ruby:2.6.3
#ruby version specification
#gem installation
RUN apt-get update -qq && \
apt-get install -y build-essential \
libpq-dev \
nodejs
#cron installation
RUN apt-get install -y cron
RUN mkdir /my_app
WORKDIR /my_app
COPY Gemfile /my_app/Gemfile
COPY Gemfile.lock /my_app/Gemfile.lock
RUN gem install bundler
RUN bundle install
COPY . /my_app
#Write crontab with whenever
RUN bundle exec whenever --update-crontab
#Run cron in the foreground
CMD ["cron", "-f"]
docker-compose.yml
version: '2'
services:
db:
image: mysql:8.0.19
command:
--default-authentication-plugin=mysql_native_password
volumes:
- ./mysql-confd:/etc/mysql/conf.d
- mysql-data:/var/lib/mysql #For data persistence
ports:
- "3306:3306"
restart: always
environment:
MYSQL_ALLOW_EMPTY_PASSWORD: 1
# MYSQL_DATABASE: app_development
MYSQL_USER: root
# MYSQL_PASSWORD: password
TZ: Asia/Tokyo
app:
build: .
command: bundle exec rails s -p 3000 -b '0.0.0.0'
volumes:
- .:/my_app
- bundle:/usr/local/bundle
ports:
- "3000:3000"
links:
- db
volumes:
mysql-data:
bundle: #You don't have to rebuild after bundle install
config/schedule.rb
#Rails because you need to start rails whenever.Use root
require File.expand_path(File.dirname(__FILE__) + "/environment")
#It does the environment variables nicely
ENV.each { |k, v| env(k, v) }
#File to write logs
set :output, error: 'log/crontab_error.log', standard: 'log/crontab.log'
set :environment, :development
#Every 2 minutes`sample_task`of`scheduled_task`To run
every 2.minutes do
rake 'sample_task:scheduled_task'
# runner "Test.yakisoba", :environment => :development #runner example
end
/lib/tasks/sample_task.rb
namespace :sample_task
desc "scheduled_task"
task scheduled_task: :environment do
.....Function you want to execute
end
end
end
Recommended Posts