Windows 服务不触发 OnStart 事件

Windows Service Does Not Fire OnStart Event

我有 windows 服务申请。但是 OnStart 事件不会触发。每次我停止服务时,只会触发 OnStop 事件。我错过了什么?

    public partial class Scheduler : ServiceBase
    {
        private Timer timer1 = null;

        public Scheduler()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            timer1 = new Timer();
            timer1.Interval = 5000;
            timer1.Elapsed += new ElapsedEventHandler(this.timer1_Tick);
        }

        protected override void OnStop()
        {
            timer1.Enabled = false;
            Library.Log(String.Format("Windows service stopped"));
        }

        private void timer1_Tick(object sender, ElapsedEventArgs e)
        {
            Library.Log(String.Format("Scheduler service {0}", DateTime.Now));
        }
    }

OnStart 正在启动,您的计时器没有。

您必须在 OnStart 中执行 timer1.Start()timer1.Enabled = true 以使计时器开始计时。

protected override void OnStart(string[] args)
{
    Library.Log("Windows service started");
    timer1 = new Timer();
    timer1.Interval = 5000;
    timer1.Elapsed += new ElapsedEventHandler(this.timer1_Tick);
    timer1.Start()
}