问题描述
我想每分钟在我的controller.rb文件中运行一个特定的方法。我正在使用任何宝石的铁路,但我有点困惑,如何做到这一点。
目前在schedule.rb中有:
分钟做
runnerServer.update_all_servers
end
什么是runner命令。有人可以解释这个命令究竟是什么?从我的理解,它调用一个Model.ModelMethod,但我需要调用一个方法在application_controller.rb中调用update_all_servers()。有可能做到这一点吗?或者我必须将我的application_controller.rb中的任何内容移动到一个模型文件(如位于/models/server.rb中的模型文件)。
您可以在 / 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
$ c> ServerUpdater.new(@servers).update_all 在您的控制器中。
在您的cron作业中,您将调用 ServerUpdater.new(Server.all).update_all
您需要一个 update_info
方法在您的模型中将包含逻辑。
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)?
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.
这篇关于Rails每当Gem如何在Controller.rb文件中运行特定方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!