ruby - use gem 'whenever' to check the deadline - ruby-on-rails

I want to use 'whenever' this gem to check my all projects are still not out of deadline. I wrote this code but it didn't work and change status in the database. Can somebody give me some advises. Thank you for helping!
config/schedule.rb
set :environment, :development
every 1.day, at: '11:3 am' do
rake 'project:close_project'
end
app/models/project.rb
def self.close_project(dt)
# 締切日が過ぎているプロジェクトを抽出
Project.where(deadline > dt).each do |project|
# 対象プロジェクトを終了状態に
project.update!(status: 'closed')
end
end
product.rake
namespace :product do
task :close_project => :environment do
Project.close_project(Date.today)
end
end

Whenever creates jobs based on CronJob format. So to run your jobs periodically, you should run whenever command and copy and pasting the results to crontab by running crontab -e or do this task automatically just by running whenever -w.

Related

How to set rake task for delete worker using whenever gem

I've got worker which deletes all admin logs older than 1 year. I want it run once a day using gem whenever as a rake task however I'm not follow the whole logic of rake tasks. I was trying to follow this article https://medium.com/#sampatbadhe/rake-task-invoke-or-execute-419cd689c3bd how ever the big question is should I move my worker to rake file or I can I refer directly to the file where this worker is?
my worker below:
class AdminPanelLogRemoverWorker
include Sidekiq::Worker
def perform
expired_logs = AdminPanelLog.where('created_at < ?', 1.year.ago).select(:id)
expired_logs.find_in_batches do |logs_batch|
AdminPanelLog.where(id: logs_batch.map(&:id)).delete_all
end
end
end
As far I understand my schedule.rb in whenever gem should be like below:
every 24.hours do
rake 'myproject:AdminPanelLogRemoverWorker'
end
It's a worker, not a rake task, so you can do it with
every 24.hours, at: '0:00am' do
runner 'AdminPanelLogRemoverWorker.perform_async'
end

Scheduler works once

The project uses the task scheduler - gem 'clockwork'. Capistrano executes the hook:
after :'deploy:finished', :'clockwork:restart'
The scheduler is triggered once (after this hook), runs all rake tasks, then tasks are not started. No matter how much I put an interval, in a day or 5 minutes, the task does not start anymore. Gem 'daemons' is installed. I will be glad to any help!
UPDATE
require 'clockwork'
require_relative './boot'
require_relative './environment'
module Clockwork
handler do |job|
puts "Running job: #{job}"
end
every(1.minute, 'job:some_task') do
rake_task('job:some_task')
end
def rake_task(task_name)
AppName::Application.load_tasks
Rake::Task[task_name].invoke
end
configure do |config|
config[:sleep_timeout] = 3600 # 1 hour
config[:logger] = Logger.new("#{Rails.root}/log/clockwork.log")
config[:tz] = 'UTC'
config[:max_threads] = 15
config[:thread] = true
end
end
My guess is you're not running clockwork as a daemon, hence why it runs only once. Have a look at this gist
desc "Start clockwork"
task :start, :roles => clockwork_roles, :on_no_matching_servers => :continue do
run "daemon --inherit --name=clockwork --env='#{rails_env}' --output=#{log_file} --pidfile=#{pid_file} -D #{current_path} -- bundle exec clockwork config/clockwork.rb"
end
You could always SSH into your deployment and either check the list of PID or check in your rails application the temporal file that stores clockwork's PID:
.../tmp/pids/clockwork.pid
Alternatively check clockwork's logs:
.../log/clockwork.log

Update database monthly ruby on rails?

I have a table "Point" with an integer column "monthly_point", and a table "User" with an integer column "Give_Point". I want to update the value of "Give_Point" is value of "monthly_point" every month. How can i do that? Thanks all.
There is a gem for such tasks, called sidetiq
It uses sidekiq for background jobs.
Here is an example
class MonthlyPointWorker
include Sidekiq::Worker
include Sidetiq::Schedulable
recurrence { monthly }
def perform
# do your work here
end
end
Whenever just puts your tasks into the crontab and executes it using cron.
It's up to you which one you will use for your needs.
You should use cron-jobs to achieve this so, use the whenever gem
Just add gem 'whenever', require: false to your Gemfile and run bundle install.
Then within your application’s root directory, run the following command:
`bundle exec wheneverize`
This will add a schedule file to your config folder (config/schedule.rb). This file is where you set up your scheduled tasks. You can use regular cron scheduling, or you can use a more idiomatic DSL for scheduling. The following examples are take from the gem’s README.md:
every 3.hours do
runner "MyModel.some_process"
rake "my:rake:task"
command "/usr/bin/my_great_command"
end
every 1.day, :at => '4:30 am' do
runner "MyModel.task_to_run_at_four_thirty_in_the_morning"
end
every :hour do # Many shortcuts available: :hour, :day, :month, :year, :reboot
runner "SomeModel.ladeeda"
end
every :sunday, :at => '12pm' do # Use any day of the week or :weekend, :weekday
runner "Task.do_something_great"
end
every '0 0 27-31 * *' do
command "echo 'you can use raw cron syntax too'"
end`
Once you’ve set up your scheduled tasks in config/schedule.rb, you still need to apply them to your crontab. From your terminal, use the whenever command to update your crontab:
Change to your application's directory.
cd /my/app
View config/schedule.rb converted to cron syntax
bundle exec whenever
Whenever Gem

rails whenver gem , running a command only if certain condition passes.

We are using whenever gem with rails on our project. I understand that we can schedule a command using whenever gem like this.
every 1.day, :at => '6:00 am' do
command "echo 'hello'"
end
but my problem is that i want to execute this command only when some condition is met. something like this.
every 1.day, :at => '6:00 am' do
if User.any_new_user?
command "echo 'hello'"
end
end
how can we achieve this with the whenever and rails?
One possible solution i can think of is that i create a runner for this and check that condition there.Something like:
every 1.day, :at => '6:00 am' do
runner "User.say_conditional_hello"
end
and inside my user model:
def self.say_conditional_hello
`echo "Hello"`
end
Any suggestions on this approach or any new approach will be really helpful.
Thanks in advance!.
if you want to only schedule the task if the condition is true then I don't think its possible you can schedule a task then when its time for running the task, the code can decide if it should be run or not, depending on your conditions
One possible solution i can think of is that i create a runner for this and check that condition there.Something like:
Yes this is one way of handeling this, however IMO the best behavior when using whenever is creating a rake task that checks for conditions then executes your code or perform your job
Something like:
Rake Task
namespace :user do
desc "description"
task check_for_new: :environment do
if User.any_new_user?
# code
end
end
end
in your schedule.rb file
every 1.day, :at => '6:00 am' do
rake "user:check_for_new"
end

Cron job in ruby on rails not work

I followed the railscast http://railscasts.com/episodes/164-cron-in-ruby but I cant seem to make it worked.
I have schedule.rb in my config.
I wished to refresh my Database.count everyday in my homepage.
I cannot find the deploy.rb in my folder. Where is it?
For testing purpose, I changed it to every 2 seconds.
[schedule.rb]
every '2 * * * *' do
rake "pages_controller:home"
end
[pages_controller.rb]
class PagesController < ApplicationController
def home
#title = "Home"
#companies = Company.find(:all, :limit => 20)
#count = Company.count
end
I have put
gem 'whenever', :require => false
in my gemfile. What have gone missing?
I have used cron job but i run it as rake task please you can try it
every 3.minutes do
set :environment, 'development'
rake "daily",:output => {:error => 'error.log', :standard => 'cron.log'}
end
And my task is like
require 'rubygems'
task :daily => :environment do
puts "i am fine"
# do your code
end
If cron job run fine then there will be nothing in cron.log.Otherwise it will show you if
any error occurs and this file will be generate in your app root directory.
try it..
So... Couple things.
You need a Capfile and a config/deploy.rb to deploy your code using Capistrano and Whenver. You get this by running capify . ... You should most likely watch the railscast on capistrano deployment
Whenever is using configured like:
schedule.rb
every 1.day, :at => '4:30 am' do
runner 'Rails.cache.clear'
end
I really don't think rake "pages_controller:home is going to work unless this is something you've already created elsewhere. I'm further assuming you are caching this page, and that's why you need to refresh the cache.
Finally, you're setting your environment to development, which makes me think you are not deploying this, but instead just wanting to reset the cached home page... So just run rake cache:clear

Resources