views:

1346

answers:

4

Guys,

I wrote a VB.NET Windows Service, which works fine. I have only one issue with it. I want the service to execute on the half hour and top of the hour marks (e.g. 9:00, 9:30, 10:00, 10:30, 11:00, etc etc etc). I am using the following code:

Protected Overrides Sub OnStart(ByVal args() As String)
    ' Add code here to start your service. This method should set things
    ' in motion so your service can do its work.
    Dim oCallBack As New TimerCallback(AddressOf TimedEvent)
    oTimer = New System.Threading.Timer(oCallBack, Nothing, 300000, 300000)
    EventLog.WriteEntry("CCFinalizeService has begun successfully." , _
                        System.Diagnostics.EventLogEntryType.Information)

End Sub

This code works, however, if the service starts at, say, 10:15, then it executes at 10:15, 10:45, 11:15, 11:45. How do I make it so it always executes on the 30 minute and top of the hour marks?

+2  A: 

You could change it so that, at startup, it figures out the time required to go to a half hour increment based off the current time. Basically, your first timer would be <300000, then switch to every 300000.

Alternatively, you might want to consider using the Windows Task Scheduler instead of doing this as a service. The task scheduler lets you specify specific times to run an application.

Reed Copsey
+1 for scheduled task vs service
Joel Coehoorn
Doesn't a scheduled task is that it requires the system to be logged on?
BenAlabaster
@balabaster: No. The Task Scheduler runs as a service, and allows tasks to be setup to run with no users logged in, as well. You can set it up to only schedule tasks when a user is logged in, but you can also setup to run at system startup, specific times, etc. It's fairly flexible. See the link for details.
Reed Copsey
A: 

Probably the easiest solution would be to test, at service startup, the current time, via the Date.Now property. You can then use a second timer to start the first timer, but set the Interval on the second timer to fire only at the next 1/2 hr or full hour mark.

Alternately, in your startup routine, have an infinite while loop that tests to see if the current time is on your mark. If not, System.Threading.Thread.Sleep(1000) and test again.

Good luck!

Mike
A: 

Maybe something like this??

 If Now.Minute <> 0 Or Now.Minute <> 30 Then
    Thread.Sleep((30 - Now.Minute) * 60 * 1000)
 End If
Jon
A: 

You just need to modify the dueTime parameter in the Timer creation method

Dim now As Date = DateTime.Now
Dim dueTime As Integer ' milliseconds to the next half-hour
dueTime = 1800000 - (now.Minute Mod 30) * 60000 - now.Second * 1000 - now.Millisecond
oTimer = New System.Threading.Timer(oCallBack, Nothing, dueTime, 1800000)
Patrick McDonald
Knew it had to be something as simple as this. Thanks!
icemanind