Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInterval() equivalent for ruby

Tags:

ruby

In JavaScript you can do:

setInterval(func,delay); 

I can't seem to find anything on google for what I'm actually looking for. Is there a ruby equivalent for this? Thanks in advance.

like image 765
anakin Avatar asked Oct 17 '13 00:10

anakin


2 Answers

You can do something like it:

Thread.new do
  loop do 
    sleep delay
    # your code here
  end
end

Or you can define a function:

# @return [Thread] return loop thread reference
def set_interval(delay)
  Thread.new do
    loop do
      sleep delay
      yield # call passed block
    end
  end
end

When you want to stop the set_interval, you just call any of these methods: exit, stop or kill.

You can test it into console (irb or pry):

t1 = Time.now; t = set_interval(2.5) {puts Time.now - t1}
> 2.500325
> 5.000641
> 7.500924
...
t.kill # stop the set_interval function
like image 129
Thiago Lewin Avatar answered Nov 12 '22 19:11

Thiago Lewin


I use rufus-scheduler:

scheduler = Rufus::Scheduler.new
scheduler.every '5m' do
    # Some Fancy Code Logic That Runs Every 5 Minutes
end
like image 37
Ben Aubin Avatar answered Nov 12 '22 20:11

Ben Aubin