在Ruby上执行带有随机延迟的代码

时间:2015-12-28 16:35:27

标签: ruby loops random time

我想用随机延迟执行我的函数 我尝试了几种解决方案,但没有任何效果

我的代码看起来像这样

for i in (1..10)
  puts "Love Stack"
end

我试过这个:

def every_n_seconds(n)
  loop do
      before = Time.now
      yield
      interval = n-(Time.now-before)
      sleep(interval) if interval > 0
  end
end

for i in (1..10)
  a = [1,2,3,4,5,6,7,8,9]
  a.shuffle!
  b = a[1]
    every_n_seconds(b) do
      for i in (1..10)
        puts "test"
      end
    end
end

有解决方案吗?

1 个答案:

答案 0 :(得分:1)

以下是一种可能的方法 - 此处rand(10)用于生成09之间的随机数,该值用于休眠这么多秒。 sleep(n)将在n秒内休眠。

def with_delay(n)
    puts "#{Time.new} Will sleep for #{n} seconds"
    sleep(n)

    puts "#{Time.new} Yielding now..."
    yield
end

5.times do
    with_delay(rand(10)) do
        puts "   Thanks for yielding"   
    end
end

输出:

2015-12-28 22:53:59 +0530 Will sleep for 1 seconds
2015-12-28 22:54:00 +0530 Yielding now...
   Thanks for yielding
2015-12-28 22:54:00 +0530 Will sleep for 0 seconds
2015-12-28 22:54:00 +0530 Yielding now...
   Thanks for yielding
2015-12-28 22:54:00 +0530 Will sleep for 7 seconds
2015-12-28 22:54:07 +0530 Yielding now...
   Thanks for yielding
2015-12-28 22:54:07 +0530 Will sleep for 5 seconds
2015-12-28 22:54:12 +0530 Yielding now...
   Thanks for yielding
2015-12-28 22:54:12 +0530 Will sleep for 2 seconds
2015-12-28 22:54:14 +0530 Yielding now...
   Thanks for yielding