7

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.

anakin
  • 367
  • 3
  • 18
  • http://stackoverflow.com/questions/13791964/how-do-i-make-a-ruby-script-run-once-a-second has the same question asked. This gem [whenever](https://github.com/javan/whenever) might help you – addicted20015 Jul 10 '14 at 13:36

2 Answers2

18

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
Thiago Lewin
  • 2,810
  • 14
  • 18
1

I use rufus-scheduler:

scheduler = Rufus::Scheduler.new
scheduler.every '5m' do
    # Some Fancy Code Logic That Runs Every 5 Minutes
end
David Bodow
  • 688
  • 5
  • 15
Ben Aubin
  • 5,542
  • 2
  • 34
  • 54
  • 1
    Great call, though `Rufus::Scheduler#interval` may be more appropriate if you need the same fixed time delay as the JS `setInterval` https://github.com/jmettraux/rufus-scheduler#in-at-every-interval-cron – David Bodow Aug 14 '20 at 18:21