I want a method to be executed every 5 minutes, I implemented whenever for ruby (cron). But it does not work. I think my method is not accessible.
The method I want to execute is located in a class. I think I have to make that method static so I can access it with MyClass.MyMethod
. But I can not find the right syntax or maybe I am looking in the wrong place.
Schedule.rb
every 5.minutes do
runner "Ping.checkPings"
end
Ping.rb
def checkPings
gate = Net::Ping::External.new("10.10.1.1")
@monitor_ping = Ping.new()
if gate.ping?
MonitorPing.WAN = true
else
MonitorPing.WAN = false
end
@monitor_ping.save
end
You cannot have static methods in Ruby. In Ruby, all methods are dynamic. There is only one kind of method in Ruby: dynamic instance methods.
Really, the term static method is a misnomer anyway. A static method is a method which is not associated with any object and which is not dispatched dynamically (hence "static"), but those two are pretty much the definition of what it means to be a "method". We already have a perfectly good name for this construct: a procedure.
Instead of extending
self
for the whole class, you can create a block that extends from self and define your static methods inside.you would do something like this :
So in your example, you would do something like this :
and you can call it as follows :
Ping.checkPings
To declare a static method, write ...
... or ...
Change your code from
to
Note there is self added to the method name.
def checkPings
is an instance method for the class MyModel whereasdef self.checkPings
is a class method.You can use static methods in Ruby like this:
Also notice that you're using a wrong naming convention for your method. It should be
check_pings
instead, but this does not affect if your code works or not, it's just the ruby-style.