如何让 Ruby 脚本每秒运行一次? [英] How do I make a Ruby script run once a second?

查看:32
本文介绍了如何让 Ruby 脚本每秒运行一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要每秒运行一次的 Ruby 脚本.我正在使用 Ruby 脚本来跟踪目录中文件的修改,并希望该脚本在实时"时间跟踪更新.

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.

基本上,我希望我的脚本执行与在 Unix shell 上运行top"相同的事情,其中​​屏幕大约每秒更新一次.Ruby 中的 setInterval 是否与 JavaScript 中的相同?

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?

推荐答案

有几种方法可以做到这一点.

There are a few ways to do this.

快速而肮脏的版本:

  1. 贝壳(朝鲜语):

  1. shell (kornish):

while :; do
   my_ruby_script.rb
   sleep 1
done

  • 观看(1):

  • 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.

    在红宝石中:

    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.

    这是一个 ruby​​ 函数,它可以确保(几乎)每秒准确地调用该函数,只要该函数花费的时间不超过一秒:

    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
    

    像这样使用它:

    secondly_loop { my_function }
    

    这篇关于如何让 Ruby 脚本每秒运行一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆