C#在特定时间调用任务组

时间:2017-01-16 14:10:38

标签: c#

我有下面的代码,它与我完美配合,并行运行,在特定时间执行所需的任务,在我的情况下是midnigh

using System;
using System.Threading.Tasks;

namespace COREserver{
    public static partial class COREtasks{   // partial to be able to split the same class in multiple files
         public static async void RunSheduledTasks_12AM(){
                TimeSpan MIDNIGHT = new TimeSpan(0,00,00,00,000); //set when run event (ex. 18:16:53.123)
                DateTime endDate = DateTime.Today.Add(MIDNIGHT);
                if(endDate<DateTime.Now) endDate = endDate.AddDays(1.0);
                while (true)
                {
                    TimeSpan duration = endDate.Subtract(DateTime.Now);
                    if(duration.TotalMilliseconds <= 0.0)
                    { 
#region MIDNIGHT Tasks  
                        Parallel.Invoke(
                            () => task1(),
                            () => task2(),
                            () => task3()
                        );
#endregion MIDNIGHT Tasks
                        endDate = endDate.AddDays(1.0);
                        continue;
                    }
                    int delay = (int)(duration.TotalMilliseconds/2);
                    await Task.Delay(delay>0?delay:0);
                }
          }
    }
}

我发现我需要做同样的事情,其他时间段,如值班的开始时间(上午7:00),中午和上班时间(下午5:00)

有没有办法避免重新编码everthing,比如回调函数,所以我可以像我这样调用我的任务:

midnight(MIDNIGHT, task1, task2,...)
midday("12:00:00", task5, task6, ..)

或类似的东西:

switch(time){
  casse MIDNIGHT: .. run task1, task2,..
  case "12:00:00": .. run task5, task6,.. 

}

由于

1 个答案:

答案 0 :(得分:2)

除了使用像Quartz.NET这样的现成解决方案(正如Stephen在你的问题的评论中所建议的那样),你可以简单地将你的开始时间和任务列表作为参数传递给你的方法:

public static async void RunSheduledTasks(TimeSpan endTime, params Action[] tasks)
{
    DateTime endDate = DateTime.Today.Add(endTime);
    if (endDate < DateTime.Now) 
        endDate = endDate.AddDays(1.0);
    while (true)
    {
        TimeSpan duration = endDate.Subtract(DateTime.Now);
        if(duration.TotalMilliseconds <= 0.0)
        { 
            Parallel.Invoke(tasks);
            endDate = endDate.AddDays(1.0);
            continue;
        }
        int delay = (int)(duration.TotalMilliseconds / 2);
        await Task.Delay(delay > 0 ? delay : 0);
    }
}

然后您可以这样称呼它:

await COREtasks.RunSheduledTasks(new TimeSpan(0,00,00,00,000), 
                                 () => Console.WriteLine("Test1"), 
                                 () => Console.WriteLine("Test2"));