Rails Whenever Gem How to Run Specific Method in Controller.rb File

泄露秘密 提交于 2019-12-07 14:43:59

问题


I am looking to run a specific method inside my controller.rb file every minute. I am looking at using the whenever gem for rails but I am a bit confused on how to do this.

Currently in schedule.rb I have:

every 1.minutes do 
runner "Server.update_all_servers"
end

I am unsure exactly what the runner command does. Could someone explain what this command exactly does? From my understanding it calls a Model.ModelMethod but I need to call a method in application_controller.rb called update_all_servers(). Is it possible to do this? Or would I have to move whatever is inside my application_controller.rb to a model file (such as the one located in /models/server.rb)?


回答1:


You can create a Server class in /lib:

class ServerUpdater
    attr_accessor :servers

    def initialize(servers = nil)
        @servers = servers || Server.all
    end

    def update_all
        servers.find_each { |server| server.update_info }
    end
end

Then you can call ServerUpdater.new(@servers).update_all in your controller.

In your cron job, you would call ServerUpdater.new(Server.all).update_all

And you would need an update_info method in your model that would contain the logic.




回答2:


I had the same question and I solved it straight forward and didn't have to add anything in lib so I wanted to share:

In your case you want to call a controller action, all you do is have all your logic in the model method and that's best practice anyway. The runner can then simply call the model method:

every 1.minutes do 
  runner "Server.update_all_servers"
end

Server.update_all_servers has to be a method in your Server model and not a controller action.



来源:https://stackoverflow.com/questions/12305767/rails-whenever-gem-how-to-run-specific-method-in-controller-rb-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!