【问题标题】:Calculating task start times计算任务开始时间
【发布时间】:2009-08-01 07:31:04
【问题描述】:

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

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

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

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

那么最好/最快的方法是什么? C# 解决方案的加分点,但这对于任何语言来说都足以成为一个有趣的难题:)

【问题讨论】:

    标签: algorithm scheduling


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

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

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

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

      【讨论】:

        【解决方案3】:

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

        这应该在 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);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-03-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多