Reputation: 111
I have inherited a Windows service to enhance at my company. Currently, the service prints a report daily of specific records in a database at a designated start time. I am adding a condition to set a second start time to run the same report omitting specific records. The problem I am running into is that I set the two separate start times (generally about 15 minutes apart), and it appears to be skipping over the first start time and only running the second one if the report files already exist.
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;
}
}
I can't figure out why this first one is getting skipped. Both will check if the file exists and print it if it doesn't. The next time it runs, the second report will print on it's scheduled time, but the first one gets skipped. I can't seem to figure out what I'm missing.
Upvotes: 2
Views: 3268
Reputation: 1899
Is there any chance that you are using the wrong timer? I remember there were about 2 or 3 types of timers in .Net:
System.Timers.Timer
System.Thread.Timer
System.Windows.Forms.Timer
I believe in windows service you should use one of the first two, more likely System.Timers.Timer as it provides thread safetiness via the SynchronizationObject property: System.Timers.Timer vs System.Threading.Timer
Upvotes: 2