How to program Windows Service with the Timer

Corey Fleig 80 Reputation points
2025-06-12T00:18:49.5933333+00:00

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
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,264 questions
0 comments No comments
{count} votes

Accepted answer
  1. SENTHILNATHAN SAKTHIVEL 75 Reputation points
    2025-06-12T09:54:55.7933333+00:00

    Have u tried running the job in a separate thread?


2 additional answers

Sort by: Most helpful
  1. 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.


  2. 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.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.