Ruby:力兰德频率

发布于 2024-12-22 10:34:36 字数 134 浏览 0 评论 0原文

我必须在随机选择的时间运行一段代码,但例如我必须每天运行一次。该程序并不是一直运行,所以我不能真正强迫它每小时运行并执行类似 if rand(1..24) == 1

我怎样才能设法拥有这种类型频率而不是一直运行?

I have to run a piece of code at randomly chosen times but I have to run it about once a day for instance. The program is not running all time so I can't really force it to run every hour and do something like if rand(1..24) == 1

How can I manage to have this kind of frequency without running it all time ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

_蜘蛛 2024-12-29 10:34:37

程序以某种方式需要考虑自上次运行以来所经过的时间,因此未执行的时间越长,程序执行的可能性就越大。使用睡眠的示例:

def diff_in_hours(time1, time2)
  ((time1 - time2) / 3600) 
end

start = Time.now
loop do
  hours_since_last_run = diff_in_hours(Time.now, start).to_i
  # execution gets more and more likely the longer the last
  # run is in the past
  execute if [0, nil].include? rand(0..(24 - hours_since_last_run))
  sleep(60*60) # sleep one hour
end

The program somehow needs to take the passed time since the last run into consideration, so that it gets more likely that it executes the longer it has not executed. Example using sleep:

def diff_in_hours(time1, time2)
  ((time1 - time2) / 3600) 
end

start = Time.now
loop do
  hours_since_last_run = diff_in_hours(Time.now, start).to_i
  # execution gets more and more likely the longer the last
  # run is in the past
  execute if [0, nil].include? rand(0..(24 - hours_since_last_run))
  sleep(60*60) # sleep one hour
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文