我有一个如下的要求(相信我,我太老了,做不了家庭作业咧嘴笑)
我有一堆以不同频率运行的任务。 他们还有一个开始“种子”日期/时间。 起始种子是过去的某个时间,可能是一分钟前,也可能是 5 年前。
我需要使用开始种子日期/时间和频率来计算任务的下一次运行时间 - 它不能简单地是“现在”+任务频率(对于那些在 MS SQL Server 上计划了作业的人来说,这是一个熟悉的概念)
现在,愚蠢的方法是获取起始种子并不断添加频率,直到它变得大于“现在”。 这并不是最佳选择。 最简单的方法是获取开始种子日期,将其更改为今天的日期并保留时间不变,然后添加频率直到它大于现在,但这假设频率是 24 小时的倍数。
那么最好/最快的方法是什么? C# 解决方案的加分项,但这足够通用,可以为任何语言制作一个有趣的谜题:)
I have a requirement that goes as follows (trust me, I'm way too old for homework grin)
I have a bunch of tasks that run with various frequencies. They also have a start "seed" date/time . The start seed is sometime in the past, could be one minute ago, could be 5 years ago.
I need to calculate the next run time for the task, using the start seed date/time and the frequency - it cannot simply be "now" + the task frequency (for those of you who have scheduled jobs on MS SQL Server this is a familiar concept)
Now the silly way to do it is to take the start seed and keep adding the frequency until it becomes greater than "now". That's hardly optimal. The naive way to do it would be to take the start seed date, change it to today's date and leave the time as is, then add the frequency until it's greater than now, but that assumes the frequency is a multiple of 24 hours.
So what's the best/quickest way to do this? Bonus points for a C# solution, but this is generic enough to make an interesting puzzle for any language :)
发布评论
评论(3)
更好的方法是获取开始时间戳和当前时间戳之间的差值,将其除以频率,将所得乘数向上舍入到最接近的整数,再次乘以频率,然后再次将其添加到开始时间戳。
向上舍入的行为将提供适当的偏移量。
A better method would be to take the difference between the start timestamp and the current timestamp, divide that by the frequency, round the resulting multiplier up to the nearest integer, multiply by the frequency again, and add that to the start timestamp once more.
The act of rounding up will provide the proper offset.
您的答案基本上是这样的:
使用上限函数可确保 next_time 将 >= 现在。
您必须进行必要的转换才能对日期执行此算术(例如,转换为 UNIX 时间,即自 1970 年 1 月 1 日以来的秒数。)
我不熟悉 C#,所以我无法提供代码,但我假设 C# 有用于处理日期/时间算术运算的日期/时间实用程序类。
Your answer would essentially be this:
Using the ceiling function ensures that next_time will be >= now.
You would have to do the necessary conversions to be able to perform this arithmetic on the dates (e.g., translate to UNIX time, which is number of seconds since Jan 1, 1970.)
I am not familiar with C# so I can't offer the code, but I assume that C# has date/time utility classes for dealing with date/time arithmetic operations.
有趣的谜题,感谢您的挑战:)
这应该在 C# 中完成。 几乎可以肯定可以精简,但它足够冗长来解释发生了什么。
Interesting puzzle, thanks for the challenge :)
This should do it in c#. Could almost certainly be slimmed down, but its verbose enough to explain whats going on.