Caleb said:
The proper answer depends on the context where this code will be used.
Do you want your whole program to stop until some target time?
But if this code runs within the context of
some larger system, which cannot afford to have the whole program be
unable to respond to events for many seconds in a row (rails, for
example), then sleep is a bad idea.
Well, I'm not really sure. The intent is to have a repetitive code ran
at quite a few different times with changing variables. The sleep option
doesn't really seem reliable and realistic, although its the only thing
so far. The code I can come up with is this:
class TestClass
def testtime(timetorun)
timetorun = @timetorun
sleep(1) while Time.now.strftime("%I:%M:%S %p") < ("#{@timetorun}")
#Somewhere code to run when Time.now = timetorun
end
end
test = TestClass.new
test.testtime("11:04:40 AM")
The problems are #1. I don't know how to link the time code to the code
to be run when the time code is fulfilled. #2. If I have a list of times
to be run, and one time is out of order, it will just sleep past the out
of order time. #3. While the code is waiting for a certain time, with
sleep, it cannot do anything else. Is there a way that I can run code
that will watch for a time to be fulfilled on many levels instead of
just waiting until a time, moving on and waiting for the next? Is it
possible to do something like this:
when test.testtime is true/finished?
run some code
end
In some cases, you might be able
to put your sleep and code_to_be_delayed in another thread, but then
you run into the problem of thread synchronization.
How would I do this?
Your example of
sleep(target_time-Time.now)
code_to_be_delayed
seems to work better, although it still shuts the whole code down for a
while.