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

前端 未结 4 355
醉话见心
醉话见心 2021-01-15 06:05

I have a windows service running. Within it the task runs currently at 7pm every day. What is the best way to have it run say fir example at 9.45am, 11.45am, 2pm, 3.45pm, 5p

相关标签:
4条回答
  • 2021-01-15 06:46

    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

    0 讨论(0)
  • 2021-01-15 06:58

    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.

    0 讨论(0)
  • 2021-01-15 07:02

    Consider using Quartz.net and CronTrigger.

    0 讨论(0)
  • 2021-01-15 07:08

    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();
        }
    
    0 讨论(0)
提交回复
热议问题