Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Whenever gem - Dynamic values

Lets say I have a cronjob like this:

every 1.day, :at => '4:30 am' do  
  runner "MyModel.task_to_run_at_four_thirty_in_the_morning"  
end  

Although, I would like to make '1.day' more dynamic, such as changing the value via a form in an administration page.

Then it could look like this:

every Constant.find(2).value, :at => '4:30 am' do 

or

@const = Constant.find(2)
every @const.span, :at => @const.time do 

Can anyone come up with an idea on how to make this work?

Obviously, the reason for this would be that I could use the values stored in the database on my site, like an message saying

<%= "The next update is in less than #{@const.time}" #or something similar %>
like image 461
Frexuz Avatar asked Jan 05 '11 09:01

Frexuz


2 Answers

Thank you idlefingers! It totally worked. Here's my solution:

require "#{RAILS_ROOT}/config/environment.rb"

@notification_daily = Constant.find_by_key("notification_daily_time_span")
every eval(@notification_daily.value), :at => @notification_daily.additional_data do
  runner "Notification.daily"
end

@notification_weekly = Constant.find_by_key("notification_weekly_time_span")
every eval(@notification_weekly.value), :at => @notification_weekly.additional_data do
  runner "Notification.weekly"
end

.value can contain for example: 1.day or :sunday
.additional_data contains the timestamp, example: 11:00am

And yes, I'm aware that I need to run --update crontab again :)
But I'll let a cronjob update itself, hehe.

like image 172
Frexuz Avatar answered Nov 17 '22 06:11

Frexuz


I've never tried, but you should be able to do this by loading up the Rails environment in whenever so that you can use your model classes. Just use require File.dirname(__FILE__) + "./environment" (or "./application" for Rails 3) in your schedule.rb, assuming your schedule.rb is in the config dir.

However, since all whenever does is generate lines in the crontab, any changes made to any Constant would require running whenever --update-crontab again.

like image 8
idlefingers Avatar answered Nov 17 '22 06:11

idlefingers