我已经关注了Windows服务的代码片段,并没有达到timer1_Elapsed
这是执行我的逻辑的主要功能。我已经使用调试完成了代码。我想征求专家的意见。
public partial class myService : ServiceBase
{
public myService()
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("myService Source"))
{
System.Diagnostics.EventLog.CreateEventSource(
"myService Source", "myService Log");
}
eventLog1.Source = "myService Source";
eventLog1.Log = "myService Log";
}
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("myService service started on " + DateTime.Now.ToString());
System.Diagnostics.Debugger.Launch();
System.Diagnostics.Debugger.Launch();
string ProcessHour = ConfigurationManager.AppSettings["ProcessHour"];
int intProcessHour = Convert.ToInt32(ProcessHour);
DateTime dtNow = DateTime.Now;
if (dtNow.Hour < intProcessHour)
{
DateTime dtToday = DateTime.Today;
DateTime dtStartDateTime = dtToday.AddHours(Convert.ToDouble(ProcessHour));
System.TimeSpan diff = dtStartDateTime.Subtract(DateTime.Now);
timer1.Interval = diff.TotalMilliseconds;
timer1.Start();
}
else
{
DateTime dtToday = DateTime.Today;
DateTime dtStartDateTime = dtToday.AddDays(1).AddHours(Convert.ToDouble(ProcessHour));
System.TimeSpan diff = dtStartDateTime.Subtract(DateTime.Now);
timer1.Interval = diff.TotalMilliseconds;
timer1.Start();
}
}
protected override void OnStop()
{
eventLog1.WriteEntry("myService service stopped on " + DateTime.Now.ToString());
}
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
timer1.Stop();
string StartTimer, EndTimer;
StartTimer = DateTime.Now.ToString();
eventLog1.WriteEntry("myService timer1_Elapsed begin on " + DateTime.Now.ToString());
/*Some Logic*/
}
catch (Exception ex)
{
}
}
}
修改 InitializeComponent()确实包含该函数但仍然无法命中。
private void InitializeComponent()
{
this.eventLog1 = new System.Diagnostics.EventLog();
this.timer1 = new System.Timers.Timer();
((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Interval = 60000;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
//
// myService
//
this.ServiceName = "myService";
((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();
}
答案 0 :(得分:0)
除非你是在设计师那里做过的(也许它可能会进入InitializeComponent()
),你似乎错过了把事件附加到timer1
timer1.Tick += timer1_Elapsed;
这应该使代码像你期望的那样工作
如果即使这样做不起作用,请考虑使用课程System.Timers.Timer
。这是一个可以帮助您理解Timer类之间差异的参考
https://web.archive.org/web/20150329101415/https://msdn.microsoft.com/en-us/magazine/cc164015.aspx