Calculate number of minutes until next run
This should be trivial, but my brain is running into a brick wall tonight.
I have a process that will run once, then every n
minutes of an hourly offset.
EG, 15 minut开发者_运维问答es means run on the hour (say, 1), then 1:15, 1:30, 1:45, etc.
If the execution interval is 15, the initial execution is at 1:07 and runs until 1:11, the wait for the next execution will be in 4 minutes.
If the execution interval is 15, the initial execution is at 1:07 and runs until 1:16, the wait for the next execution will be 14 minutes (execution times do not overlap).
So, after every run (of an varying length), how do we calculate the number of minutes to wait until the next execution?
I'm not putting any sample code in here, because I don't have anything that will pass my unit tests (I'm not so brain-dead that I can't write those !).
I've tagged this as C#
since that's what I'm coding in, but I would expect the solution to be language-agnostic.
Okay, just as I hit submit on the question, I had an epiphany.
Given currentMinute
>= 0 and executionInterval
>= 1
absolute-value((currentMinute modulo executionInterval) - executionInterval)
or, in C#
return Math.Abs((currentMinute % executionInterval) - executionInterval);
so far, my unit-tests are passing on this one. So, either it is correct, or I don't have enough tests....
Convert to minutes, mod by 15, add 1, multiply by 15, subtract original number.
// n is time in minutes
int m = n%exec_time;
m += 1;
return m*exec_time - n;
That may be a little more powerful solution that you want, but if you want the end user to specify the interval, you might want to give him more than just "specify interval in minutes: " option. Take a look at Cron format. It allows you to specify any kind of weird complicated time intervals.
The good news is that there are a lot of implementations of crontab libraries, some of them are for C#. Check NCrontab, it has useful methods like GetNextOccurences
which will calculate the dates based on interval input and current time. If you use it, you might end up saving time on implementing this feature while making it more rich and useful.
- M = Minutes until next run
- To = Total minutes that have transpired since first run (In c# subtract current time from first run time and get TimeSpan.TotalMinutes)
I = Interval in minutes
M = I - (To % I)
精彩评论