Cydonia7
Cydonia7

Reputation: 3836

Ruby : force rand frequency

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 ?

Upvotes: 0

Views: 137

Answers (1)

Niklas B.
Niklas B.

Reputation: 95328

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

Upvotes: 1

Related Questions