Have u tried running the job in a separate thread?
How to program Windows Service with the Timer
I have a service in C#, runs great, but I have trouble with the time offset. I want the event to fire every hour, but if the job is 2 minutes long, it bumps up the next hour by 2 minutes.
Example:
Fire event at 7am. If Job runs for 2 minutes. then fire again at 8am, not 8am plus 2 minutes.
I suppose I need to subtract the job from 1 hour, but the milliseconds need to zero out too.
How can i deal with this?
.NET Runtime
2 additional answers
Sort by: Most helpful
-
AgaveJoe 30,121 Reputation points
2025-06-12T12:18:47.75+00:00 It sounds like you're aiming for precise hourly execution, not just running code an hour later. A solid strategy is to check the current time after your code runs, then use a little math to calculate the exact delay needed to hit the start of the next hour.
Another approach for this would be to periodically sample the system's current time.
For example, by checking every 30 seconds, you'd be able to execute your code within 30 seconds before or after the hour. To achieve greater precision, you could increase the frequency of your time samples.
-
Bruce (SqlWork.com) 77,476 Reputation points Volunteer Moderator
2025-06-12T15:31:18.0166667+00:00 It sounds like the job is scheduling the next job, rather than the timer just firing every hour. If the job can take more than hour, and two cannot overlap (use threads to support overlap), then just use math to schedule the next run.