sleep for lesser of two values

E

Earle Clubb

I have a loop that runs for a variable amount of time, as defined by
@duration. I need to re-execute the command every 15 seconds for the
length of @duration, which is a float and can have any value. Can
anyone think of a more elegant way to do this than the code below?

end_time = Time.now + @duration
while (t = Time.now) < end_time
# execute command
sleep((15 < (end_time - t)) ? 15 : (end_time - t))
end


Thanks,
Earle
 
P

Pete Elmore

I have a loop that runs for a variable amount of time, as defined by
@duration. I need to re-execute the command every 15 seconds for the
length of @duration, which is a float and can have any value. Can
anyone think of a more elegant way to do this than the code below?

end_time = Time.now + @duration
while (t = Time.now) < end_time
# execute command
sleep((15 < (end_time - t)) ? 15 : (end_time - t))
end
I don't know about elegant, but it's a little more easy to read
sleep [15, end_time - t].min
than the ?: business.
 
T

Tim Hunter

Earle said:
I have a loop that runs for a variable amount of time, as defined by
@duration. I need to re-execute the command every 15 seconds for the
length of @duration, which is a float and can have any value. Can
anyone think of a more elegant way to do this than the code below?

end_time = Time.now + @duration
while (t = Time.now) < end_time
# execute command
sleep((15 < (end_time - t)) ? 15 : (end_time - t))
end


Thanks,
Earle


sleep([15, end_time -t].min)
 
M

MenTaLguY

I have a loop that runs for a variable amount of time, as defined by
@duration. I need to re-execute the command every 15 seconds for the
length of @duration, which is a float and can have any value. Can
anyone think of a more elegant way to do this than the code below?

end_time = Time.now + @duration
while (t = Time.now) < end_time
# execute command
sleep((15 < (end_time - t)) ? 15 : (end_time - t))
end

Maybe:

sleep [ 15, end_time - t ].min

-mental
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top