Note that there are some explanatory texts on larger screens.

plurals
  1. POSynchronizing a service with a timer
    primarykey
    data
    text
    <p>I'm trying to write a service in c# that should be run on a given interval (a timeout) from a given date. If the date is in the future the service should wait to start until the date time is reached. </p> <p>Example: </p> <ul> <li><p>If I set a timeout to be 1 hour from 21:00:00 I want the program to run every hour</p></li> <li><p>If I set a timeout to be 1 hour from 3999.01.01 21:00:00 I want the program to until date and from then run each hour</p></li> </ul> <p><strong>I have sort of achieved that with the following code, but it has some problems!</strong></p> <ol> <li><p>When I install the service (with installutil) the service is marked as <em>starting</em> because of the 'Thread.Sleep()'. This service appears to be hanging and is "installing" until started.</p></li> <li><p>The code inside 'ServiceTimer_Tick()' might take longer than the expected timeout. How can I prevent the timer stack from increasing if that happens? </p></li> </ol> <p>Alternatives I've thought of :</p> <ul> <li><p>include using the 'timeout.Interval' first time and then resetting it subsequent calls, but it doesn't feel right. </p></li> <li><p>I've also considered ditching the entire service idea and compile it as a executable and set up a scheduled tasks.</p></li> </ul> <p>Shortened example: </p> <pre><code>public Service() { _timeout = new TimeSpan(0,1,0,0); _timer = new System.Timers.Timer(); _timer.Interval = _timeout.TotalMilliseconds; _timer.Elapsed += new ElapsedEventHandler(ServiceTimer_Tick); } private void ServiceTimer_Tick(object sender, System.Timers.ElapsedEventArgs e) { lock (_obj) { // Stuff that could take a lot of time } } public static void Main() { Run(new Service()); } protected override void OnStart(string[] args) { long current = DateTime.Now.Ticks; long start = new DateTime(2010,9,15,21,0,0).Ticks; long timeout = _timeout.Ticks; long sleep; if (current &gt; start) sleep = timeout - ((current % timeout)) + (start % timeout); else sleep = start - current; Thread.Sleep(new TimeSpan(sleep)); _timer.AutoReset = true; _timer.Enabled = true; _timer.Start(); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload