当前位置: 动力学知识库 > 问答 > 编程问答 >

C# invoke group of tasks at specific time

问题描述:

I've the below code, that worked perfectly with me, and run in parallel, the required tasks at the specific time, that is midnigh in my case

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);

}

}

}

}

I found that I need to do the same, with other times period, like start time of the duty (7:00am), mid day, and end of office people time (5:00PM)

Is there a way to avoid re-coding the everthing, something like callback function, so I can call my tasks like something like this:

midnight(MIDNIGHT, task1, task2,...)

midday("12:00:00", task5, task6, ..)

or something like:

switch(time){

casse MIDNIGHT: .. run task1, task2,..

case "12:00:00": .. run task5, task6,..

}

Thanks

网友答案:

Besides using ready solution like Quartz.NET (as suggested by Stephen in the comments to your question), you could simply pass your start time and list of tasks as parameters to your method:

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);
    }
}

You could then call it like this:

await COREtasks.RunSheduledTasks(new TimeSpan(0,00,00,00,000), 
                                 () => Console.WriteLine("Test1"), 
                                 () => Console.WriteLine("Test2"));
分享给朋友:
您可能感兴趣的文章:
随机阅读: