I have a timer with interval of 1000 ms. I want to do something at random time but within a given time frame. E.g. If I specify the time frame to be for example 10 seconds, 1-10, 11-20, 21-30 and so on. This means that in the first 10 seconds something will happen between the 1st time frame 1 to 10 seconds at random. E.g. could happen in the 2nd second or the 8th second. Then again from 11 to 20 seconds something occurs again any time between the second time frame. E.g. this could be the 13th or the 15th second. Note that the timer has to be continuous e.g. from 1 to 100 seconds. Here if I specifiy the time frame to be 10 we will have ten time frames. 1-10,11-20,21-30 ....91-100. Since I need to know the exact time of the events that will occur. Therefore do not think that resetting the timer might solve the problem.
Thanks for you reply and examples with explanation are greatly appreciated.
Your question is not very clear, so let me suppose the something that will happen as a function. let's say
func1
happens in [1-10],func2
happens in [11-20] and so on.random
that outputs abool
(to judge whether execute or not).flag1
,flag2
, ...).count
), and increase it by 1 each timer.tickuse some conditions here :
and so on
I don't think any of the first 3 answers have it right, so let me try: what you are saying is that time is ticking, and in each slice of N seconds, you want one event to occur at a random time in that slice. If that is the case, then whenever the time is a multiple of N seconds, get a random number between 0 and N, and generate the event at that time. For example, in pseudo-code:
The 5 variables (time, delta_time, etc) are likely going to be data members of the class that uses the timer, and the callback will be a method of the class. Provide some code in your post for further details.
Just keep track of the actual offset for each frame, and take that into account as you generate new event times:
In other words, compute the
nextEvent
by adding the time left over in the previous interval after the previous event to the start time of the current interval, along with a random length of time within the actual interval.Then, wait enough time between now and that next event.
Finally, update the offset and interval remainder so that they can be used for the next round.
Notes:
I have a vague sense that I could have combinedI finally figured out why this was bugging me: I don't need theeventOffset
andsincePrevious
into a single value. But it's late here and I figure that's something easily left as an exercise for the reader. :)sincePrevious
in the above at all! Sigh. Code has been edited to correct for my mistake.Thread.Sleep()
for the delay. IMHO, it would be better to make the methodasync
and useTask.Delay()
instead. But I wanted to keep the example simple, and there's no way to know from the question as asked what actually is the best way to handle the delay itself.