Search code examples
c#timerwindows-services

How to create multiple timers on the run time in windows service Application


I am trying to create multiple timers on the run time based on how many tasks I will get from the database? so on the onStart() Method, am getting the data from the database and saving it in List then looping on this list and creating Timer for each task and saving this timer in List

for(int i=0;i<ScheduleTask.Count;i++)
{
    Timer t = new Timer(new TimerCallback(_=>Task(i)));
    DateTime scheduledTime = DateTime.MinValue;
    scheduledTime = DateTime.Now.AddMinutes(ScheduleTask[i].intervalMinutes);
    TimeSpan TimeSpan = scheduledTime.Subtract(DateTime.Now);                
    int dueTime = Convert.ToInt32(TimeSpan.TotalMilliseconds);
    t.Change(dueTime, Timeout.Infinite);
    timers.Add(t);
}

I want each task to call the same Method but passing to this method the index of the task but the index is always the same equals to the last index of the Scheduled Tasks

  private void Task(int index)
        {
            try
            {
                this.WriteToFile("*************" + ScheduleTask[index].Name + " Started*****************");
                //task start

                this.WriteToFile("*************" + ScheduleTask[index].Name + " Finished successfully {0}*****************");
               
            }
            catch
            {
                this.WriteToFile("*************something went wrong on index: " + index + "*****************");

            }
        }

What should I do?


Solution

  • C# refers to the local variable i, which has at the end of the loop the value of the last index. Simple hack to fix this:

        int j = i;
        Timer t = new Timer(new TimerCallback(_ => Task(j)));