How do I make a Ruby script run once a second?

ruby

Solution

There are a few ways to do this.

The quick-and-dirty versions:

shell (kornish):

while :; do
   my_ruby_script.rb
   sleep 1
done

watch(1):

shell$ watch -n 1 my_ruby_script.rb

This will run your script every second and keep the output of the most recent run displayed in your terminal.

in ruby:

while true
   do_my_stuff
   sleep 1
end

These all suffer from the same issue: if the actual script/function takes time to run, it makes the loop run less than every second.

Here is a ruby function that will make sure the function is called (almost) exactly every second, as long as the function doesn't take longer than a second:

def secondly_loop
    last = Time.now
    while true
        yield
        now = Time.now
        _next = [last + 1,now].max
        sleep (_next-now)
        last = _next
    end
end

Use it like this:

secondly_loop { my_function }

Problem

I have a Ruby script that needs to run about one time a second. I am using a Ruby script to keep track of modifications of files in a directory and want the script to track updates in "live" time. Basically, I want my script to do the same kind of thing as running "top" on a Unix shell, where the screen is updated every second or so. Is there an equivalent to `setInterval` in Ruby like there is in JavaScript?

Original source

Related problems