2
我继承了Windows服务以提升我的公司。目前,该服务每天在指定的开始时间在数据库中打印特定记录的报告。我添加了一个条件来设置第二个开始时间来运行删除特定记录的相同报告。我遇到的问题是我设置了两个单独的开始时间(通常大约相隔15分钟),它似乎跳过了第一个开始时间,并且只在报告文件已经存在时才运行第二个开始时间。Windows服务上的多个计时器未正确启动
public partial class Service1 : ServiceBase
{
Timer t1;
Timer t2;
bool Condition;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
t1 = new Timer();
t1.Interval = (1000 * 60 * 3); // 3 minutes...
t1.Elapsed += new ElapsedEventHandler(t1_Elapsed);
t1.AutoReset = true;
t1.Enabled = true;
if (Condition) //Condition is an option in the configuration to determine if this timer should even start
{
t2 = new Timer();
t2.Interval = (1000 * 60 * 3); // 3 minutes...
t2.Elapsed += new ElapsedEventHandler(t2_Elapsed);
t2.AutoReset = true;
t2.Enabled = true;
}
}
private void t1_Elapsed(object sender, ElapsedEventArgs e)
{
if (File.Exists("FileName1"))
{
string CurrentTime = DateTime.Now.ToShortDateString();
if (CurrentTime == ConfigurationManager.AppSettings["StartTime"].ToString())
{
//Print Report
}
}
else
{
//Print Report
}
}
private void t2_Elapsed(object sender, ElapsedEventArgs e)
{
if (File.Exists("FileName2"))
{
string CurrentTime2 = DateTime.Now.ToShortDateString();
if (CurrentTime2 == ConfigurationManager.AppSettings["StartTime2"].ToString())
{
//Print Report 2
}
}
else
{
//Print Report 2
}
}
protected override void OnStop()
{
t1.Enabled = false;
t2.Enabled = false;
}
}
我想不通为什么这第一个跳过。两者都会检查文件是否存在,如果不存在则打印。下次运行时,第二份报告将在预定时间打印,但第一份报告会跳过。我似乎无法弄清楚我错过了什么。
为什么你使用两个定时器呢?将任务分解为单独的方法,并从单个计时器过去的事件中调用方法,并在计时器已用事件中检查您的条件。 – JamieSee 2012-03-30 20:30:20
注意,你应该使用[计划任务](http://stackoverflow.com/questions/7394806/creating-scheduled-tasks)。服务+计时器=设计气味。通过这样做,你可以避免大部分的问题。另外,你比较时间的方式看起来超级平庸。你的问题可能在那里。很难说没有看到StartTime和StartTime2,因为它们实际上在你的配置文件中。 – Will 2012-03-30 20:30:22
我原本是将它作为一个计时器上的两个单独的方法,但我遇到了某种不同的问题,不幸的是,我不记得它是什么。此后我做了一些其他更改,以便将其更改回来可能有效。 – LDWisdom 2012-03-30 20:46:11