Back-end Engineering Articles

I write and talk about backend stuff like Ruby, Ruby On Rails, Databases, Testing, Architecture / Infrastructure / System Design, Cloud, DevOps, Backgroud Jobs, and more...

Twitter:
@daniel_moralesp

2020-01-24

Rails Rake Task Doing Correctly

Original link: https://gist.github.com/danielmoralesp/c5a56123e3aa9072c4d10a8937cb2cba

#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 [email protected]
crontab -e