Windows service scheduling to run daily once a day at 6:00 AM

后端 未结 6 2042
無奈伤痛
無奈伤痛 2020-12-10 03:17

I had created a windows service and i want that the service will Schedule to run daily at 6:00 Am. Below is the code which i had written:-

public Service1()
         


        
6条回答
  •  醉话见心
    2020-12-10 04:10

    Here is code that will run within a service every day at 6AM.

    include:

    using System.Threading;
    

    also ensure you declare your timer within the class:

    private System.Threading.Timer _timer = null;
    

    The StartTimer function below takes in a start time and an interval period and is currently set to start at 6AM and run every 24 hours. You could easily change it to start at a different time and interval if needed.

     protected override void OnStart(string[] args)
        {
            // Pass in the time you want to start and the interval
            StartTimer(new TimeSpan(6, 0, 0), new TimeSpan(24, 0, 0));
    
        }
        protected void StartTimer(TimeSpan scheduledRunTime, TimeSpan timeBetweenEachRun) {
            // Initialize timer
            double current = DateTime.Now.TimeOfDay.TotalMilliseconds;
            double scheduledTime = scheduledRunTime.TotalMilliseconds;
            double intervalPeriod = timeBetweenEachRun.TotalMilliseconds;
            // calculates the first execution of the method, either its today at the scheduled time or tomorrow (if scheduled time has already occurred today)
            double firstExecution = current > scheduledTime ? intervalPeriod - (current - scheduledTime) : scheduledTime - current;
    
            // create callback - this is the method that is called on every interval
            TimerCallback callback = new TimerCallback(RunXMLService);
    
            // create timer
            _timer = new Timer(callback, null, Convert.ToInt32(firstExecution), Convert.ToInt32(intervalPeriod));
    
        }
        public void RunXMLService(object state) {
            // Code that runs every interval period
        }
    

提交回复
热议问题