-
-
Save danielmoralesp/c5a56123e3aa9072c4d10a8937cb2cba to your computer and use it in GitHub Desktop.
Rake Task Correctly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Use whenever gem= https://github.com/javan/whenever | |
gem 'whenever', require: false | |
$ cd /apps/my-great-project | |
$ bundle exec wheneverize . | |
## review crontab | |
# way 1 | |
$ cd /apps/my-great-project | |
$ bundle exec whenever | |
# way 2 | |
crontab -e | |
#way 3 | |
crontab -l | |
## Schedule.rb | |
set :output, "log/cron.log" ## loggs | |
env :PATH, ENV['PATH'] ## set environment | |
every 5.minutes do | |
rake "ending_competition:finalize" | |
rake "ending_competition:complete" | |
end | |
## Task | |
namespace :ending_competition do | |
task finalize: :environment do | |
time = Time.zone.now | |
if Competition.where(timeline_end: (time.beginning_of_day..time.end_of_day)).present? | |
competitions = Competition.where(timeline_end: (time.beginning_of_day..time.end_of_day)) | |
competitions.update_all(status: "finalized") | |
end | |
puts "task ending_competition:finalize success" | |
end | |
task complete: :environment do | |
time = Time.zone.now | |
if Competition.where(timeline_final: (time.beginning_of_day..time.end_of_day)).present? | |
competitions = Competition.where(timeline_final: (time.beginning_of_day..time.end_of_day)) | |
competitions.each do |competition| | |
competition.add_score(competition.total_prize, competition.points) | |
competition.update!(status: "completed") | |
end | |
end | |
puts "task ending_competition:complete success" | |
end | |
end | |
## update crontab in development | |
## whatever defaults to production and will by default look for a production database. | |
## To change this behaviour you can update the crontab and set it to development as such: | |
whenever --update-crontab --set environment='development' | |
## I don't need to do this in production, because capistrano do that for me | |
## run tasks manually in development | |
rake ending_competition:finalize | |
## setup with capistrano | |
## config/deploy | |
set :whenever_roles, -> { [:app, :db, :web] } | |
set :whenever_identifier, ->{ "#{fetch(:application)}_#{fetch(:rails_env)}" } | |
## Capfile | |
require 'whenever/capistrano' | |
## when we deploy, crontab file is updated in production server | |
## to see the crontab file in production type this | |
ssh deploy@server | |
crontab -e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment