Reputation: 467
I have created a windows service which will fire an event every T interval. This event will consume a web service and call its web method. This windows service has no idea how long will the web method take to complete the execution.
What I am seeing is when interval is over, multiple instances of web method is running.I am using counters but it is not working. I don't want overlapping of web method execution.
public partial class AutoAllocation: ServiceBase
{
private Timer timer = null;
private bool runningCounter=false;
public AutoAllocation()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer = new Timer();
string timerInterval = ConfigurationManager.AppSettings["TimeInterval"];
timer.Interval = Convert.ToDouble(timerInterval);
timer.Elapsed += new System.Timers.ElapsedEventHandler(this.TimerTick);
timer.Enabled = true;
}
private void TimerTick(object sender, ElapsedEventArgs e)
{
if (runningCounter == false)
{
runningCounter = true;
EmployeeManagementService resourceMgmt = new EmployeeManagementService ();
resourceMgmt.AutoAllocateSalary();
runningCounter = false;
}
}
Upvotes: 0
Views: 71
Reputation: 29668
Try setting AutoReset to false.
This means the timer will fire once and won't fire again until you manually start it again, which you can do after your webservice call.
For example:
protected override void OnStart(string[] args)
{
string timerInterval = ConfigurationManager.AppSettings["TimeInterval"];
timer = new Timer();
timer.AutoReset = false;
timer.Interval = Convert.ToDouble(timerInterval);
timer.Elapsed += new System.Timers.ElapsedEventHandler(this.TimerTick);
timer.Start();
}
private void TimerTick(object sender, ElapsedEventArgs e)
{
EmployeeManagementService resourceMgmt = new EmployeeManagementService ();
resourceMgmt.AutoAllocateSalary();
((Timer)sender).Start();
}
This will stop any overlapping of calls, which is probably what's going on here.
Also remember that the interval is in milliseconds so if you're supplying seconds make sure its *1000
.
Upvotes: 3