0
votes

Currently, I have functions in my service which are called in different threads on timer event(every 10 mins) in window service written in 4.0 framework like this:

        public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
        {
                 Task.Factory.StartNew(() => ABC());
                 Task.Factory.StartNew(() => DEF());
                 Task.Factory.StartNew(() => GHI());
                 Task.Factory.StartNew(() => IJK());
                 Task.Factory.StartNew(() => LMN()); 
        }

I want to have different time interval/timer event for each thread. One possible solution is to create new timer object and call each function in different timer event. Is there other optimized way ? In future, if service contains 50 functions then I would have to create 50 objects of timer.

1

1 Answers

1
votes

Edit: Others have pointed out that they have used hundreds of individual timers in an application. If the number of timers isn't a system limitation then I don't know if it would be worth the extra complexity to re-use one timer for multiple intervals.


Create one timer that elapses every minute. (The interval is arbitrary, but one minute might be easier to work with.)

When it elapses, determine the total number of minutes elapsed. You could do that with

var elapsedMinutes = (DateTime.Now - _startTime).TotalMinutes
// where _startTime is when the timer started

Then, for example, if

(_elapsedMinutes % 10) == true
(_elapsedMinutes % 3) == true

Then the timer has elapsed at an interval of 10 minutes or 3 minutes, respectively.

One flaw is that depending on how long it takes between when the timer elapses and when it restarts, you could lose a few milliseconds which over a long period could add up to a minute, and eventually you could skip a minute. If that's a problem then you could account for it by shaving a few seconds off of the timer interval when the seconds portion of the elapsed time creep close to a whole minute. (That's a bit messy.)