Reputation: 944
I am building an alerter service (windows service) in c#. This service will start and do a few api calls. based on the result I get from the calls and the setting that apply to that user an other method will fire after x amount of time. This goes on until the user stops the service.
The time in between the calls to the methods can be variable. So after startup the first method call can be after 1 min, after that the next call can be after 5 min, the call after that can be after 10 min. All depends on the response I get from the API.
I have been looking into system.timers, but every example i find has a fixed time the event fires so that does not fit my needs.
Upvotes: 0
Views: 742
Reputation: 133995
Use a one-shot timer, and reset it after every call. I typically use System.Threading.Timer for this:
// When you first create the timer, set it for the initial time
Timer MyTimer = new Timer(TimerCallbackFunction, null, 60000, Timeout.Infinite);
Setting the period to Timeout.Infinite
prevents the timer from ticking multiple times. It'll just tick once and then wait indefinitely, or until you restart it.
In your timer callback, do whatever needs to be done and then reset the timer:
void TimerCallbackFunction(object state)
{
// Here, do whatever you need to do.
// Then set the timer for the next interval.
MyTimer.Change(newTimeoutValue, Timeout.Infinite);
}
This prevents multiple concurrent callbacks (if your timeout value is too short), and also lets you specify when the next tick will be.
Upvotes: 1
Reputation: 10538
Define the time variable globally and after each response reset the interval time
FYI
1 Minute = 60000 so for 10 Minutes aTimer.Interval=60000 * 10;
use it like this
//defined globally
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);
//api call goes here
aTimer.Interval=5000; // here you can define the time or reset it after each api call
aTimer.Enabled=true;
Upvotes: 2