2

我有一个要求如下(相信我,我太老了,不能做作业咧嘴笑

我有一堆以各种频率运行的任务。他们也有一个开始的“种子”日期/时间。起始种子是过去的某个时间,可能是一分钟前,也可能是 5 年前。

我需要使用开始种子日期/时间和频率来计算任务的下一次运行时间 - 它不能简单地是“现在”+任务频率(对于那些在 MS SQL Server 上安排了作业的人来说,这是一个熟悉的概念)

现在愚蠢的做法是获取起始种子并继续添加频率,直到它变得大于“现在”。这几乎不是最优的。天真的方法是获取开始种子日期,将其更改为今天的日期并保持时间不变,然后添加频率直到它大于现在,但假设频率是 24 小时的倍数。

那么最好/最快的方法是什么?C# 解决方案的加分点,但这对于任何语言来说都足够通用:)

4

3 回答 3

6

更好的方法是获取开始时间戳和当前时间戳之间的差,除以频率,将结果乘数四舍五入到最接近的整数,再次乘以频率,然后再次将其添加到开始时间戳。

四舍五入的行为将提供适当的偏移量。

于 2009-08-01T07:37:07.343 回答
0

你的答案基本上是这样的:

next_time = ceiling((now - seed)/frequency) * frequency + seed

使用上限函数可确保 next_time 将 >= now。

您必须进行必要的转换才能对日期执行此算法(例如,转换为 UNIX 时间,即自 1970 年 1 月 1 日以来的秒数。)

我不熟悉 C#,因此无法提供代码,但我假设 C# 具有用于处理日期/时间算术运算的日期/时间实用程序类。

于 2009-08-01T07:44:06.593 回答
0

有趣的谜题,感谢挑战:)

这应该在 c# 中完成。几乎可以肯定会瘦身,但它的冗长足以解释发生了什么。

// Initialise with date the event started, and frequency
DateTime startDate = new DateTime(2009, 8,1,9,0,0);
TimeSpan frequency = new TimeSpan(0, 15, 0);

// Store datetime now (so that it doesnt alter during following calculations)
DateTime now = DateTime.Now;

// Calculate the number of ticks that have occured since the event started
TimeSpan pastTimeSpan = now.Subtract(startDate);

// Divide the period that the event has been running by the frequency
// Take the remaining time span
TimeSpan remainingTimeSpan = new TimeSpan(pastTimeSpan.Ticks % frequency.Ticks);

// Calculate last occurence the event ran
DateTime lastOccurence = now.Subtract(remainingTimeSpan);

// Calculate next occurence the event will run
DateTime nextOccurence = lastOccurence.Add(frequency);
于 2009-08-01T09:00:56.113 回答