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