Windows服务不会触发OnStart事件

时间:2015-08-18 15:11:41

标签: c# windows-services

我有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));
        }
    }

1 个答案:

答案 0 :(得分:3)

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()
}