Rails - Whenever gem - Dynamic values

后端 未结 4 1804
Happy的楠姐
Happy的楠姐 2020-12-05 21:08

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  


        
相关标签:
4条回答
  • 2020-12-05 21:37

    I had the same task and decided to solve it a bit another approach. In my table have a lot of records where storing settings for schedule (daily, monthly, weekly, time)

    In schedule.rb file I added a cron job, which was running every day at 00:00 and select the records, which can be run today. And after it added to queue with sidekiq using perform_at.

    0 讨论(0)
  • 2020-12-05 21:39

    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.

    0 讨论(0)
  • 2020-12-05 21:43
    # 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
    

    Do not forget to update whenever

    0 讨论(0)
  • 2020-12-05 21:57

    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.

    0 讨论(0)
提交回复
热议问题