8

可以说我有一个这样的 cronjob:

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

虽然,我想让“1.day”更具动态性,例如通过管理页面中的表单更改值。

然后它可能看起来像这样:

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

或者

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

谁能想出如何使这项工作的想法?

显然,这样做的原因是我可以使用存储在我网站上的数据库中的值,就像一条消息说

<%= "The next update is in less than #{@const.time}" #or something similar %>
4

4 回答 4

10

谢谢各位闲人!它完全奏效了。这是我的解决方案:

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 可以包含例如:1.day:sunday
.additional_data 包含时间戳,例如:11 :00am

是的,我知道我需要再次运行--update crontab :)
但我会让 cronjob 自行更新,呵呵。

于 2011-01-06T16:09:39.437 回答
8

我从来没有尝试过,但是你应该可以通过在任何时候加载 Rails 环境来做到这一点,这样你就可以使用你的模型类。假设您的 schedule.rb 在配置目录中,只需在您的 schedule.rb 中使用require File.dirname(__FILE__) + "./environment"(或用于 Rails 3)。"./application"

但是,由于所有操作都是在 crontab 中生成行,因此对 any 所做的任何更改Constant都需要whenever --update-crontab再次运行。

于 2011-01-05T12:18:07.447 回答
7
# In rails 4
require File.expand_path('../..//config/environment.rb', __FILE__)

# This is your table by which you will get your new value 
bid_update = DynamicOfferTime.first

# Now Task As
every (bid_update.hour_value).hours do
  puts "This will repeat in every #{bid_update.hour_value} hour"
end

不要忘记随时更新

于 2015-06-26T14:02:40.023 回答
1

我有同样的任务,并决定用另一种方法来解决它。在我的表中有很多记录,其中存储日程设置(每天、每月、每周、时间)

schedule.rb文件中,我添加了一个每天 00:00 运行的 cron 作业,然后选择今天可以运行的记录。之后使用 sidekiq 添加到队列中perform_at

于 2020-02-11T10:27:40.030 回答