Windows Service - How to make task run at several specific times?

安稳与你 提交于 2019-12-01 11:08:04

In case you dont want to go for cron or quartz, write a function to find time interval between now and next run and reset the timer accordingly, call this function on service start and timeelapsed event. You may do something like this (code is not tested)

   System.Timers.Timer _timer;
    List<TimeSpan> timeToRun = new List<TimeSpan>();
    public void OnStart(string[] args)
    {

        string timeToRunStr = "20:45;20:46;20:47;20:48;20:49";
        var timeStrArray = timeToRunStr.Split(';');
        CultureInfo provider = CultureInfo.InvariantCulture;

        foreach (var strTime in timeStrArray)
        {
            timeToRun.Add(TimeSpan.ParseExact(strTime, "g", provider));
        }
        _timer = new System.Timers.Timer(60*100*1000);
        _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
        ResetTimer();
    }


    void ResetTimer()
    {
        TimeSpan currentTime = DateTime.Now.TimeOfDay;
        TimeSpan? nextRunTime = null;
        foreach (TimeSpan runTime in timeToRun)
        {

            if (currentTime < runTime)
            {
                nextRunTime = runTime;
                break;
            }
        }
        if (!nextRunTime.HasValue)
        {
            nextRunTime = timeToRun[0].Add(new TimeSpan(24, 0, 0));
        }
        _timer.Interval = (nextRunTime.Value - currentTime).TotalMilliseconds;
        _timer.Enabled = true;

    }

    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        _timer.Enabled = false;
        Console.WriteLine("Hello at " + DateTime.Now.ToString());
        ResetTimer();
    }

Consider using Quartz.net and CronTrigger.

If u are clear abt what schedule it should run..then change time interval for timer in the timeelapsed event so that it runs according to schedule..i've never tried though

I would use a background thread and make it execute an infinite loop which does your work and sleeps for 15 minutes. It would be a lot cleaner and more simple for service code than using a timer.

See this article on MSDN.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!