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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With