Windows Service to run a function at specified time

后端 未结 7 1839
一生所求
一生所求 2020-12-02 11:57

I wanted to start a Windows service to run a function everyday at specific time.

What method i should consider to implement this? Timer or using threads?

相关标签:
7条回答
  • 2020-12-02 12:25

    You can do it with a thread and an event; a timer is not necessary.

    using System;
    using System.ServiceProcess;
    using System.Threading;
    
    partial class Service : ServiceBase
    {
        Thread Thread;
    
        readonly AutoResetEvent StopEvent;
    
        public Service()
        {
            InitializeComponent();
    
            StopEvent = new AutoResetEvent(initialState: false);
        }
    
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                StopEvent.Dispose();
    
                components?.Dispose();
            }
    
            base.Dispose(disposing);
        }
    
        protected override void OnStart(string[] args)
        {
            Thread = new Thread(ThreadStart);
    
            Thread.Start(TimeSpan.Parse(args[0]));
        }
    
        protected override void OnStop()
        {
            if (!StopEvent.Set())
                Environment.FailFast("failed setting stop event");
    
            Thread.Join();
        }
    
        void ThreadStart(object parameter)
        {
            while (!StopEvent.WaitOne(Timeout(timeOfDay: (TimeSpan)parameter)))
            {
                // do work here...
            }
        }
    
        static TimeSpan Timeout(TimeSpan timeOfDay)
        {
            var timeout = timeOfDay - DateTime.Now.TimeOfDay;
    
            if (timeout < TimeSpan.Zero)
                timeout += TimeSpan.FromDays(1);
    
            return timeout;
        }
    }
    
    0 讨论(0)
提交回复
热议问题