views:

1586

answers:

3

I'm using VB 9.

I want the only thread in my Windows Service (that is set to Automatic) to start its work 5 minutes after Windows starts.

But if the user restarts the service manually, the thread should start working immediately when the service starts.

How do I achieve this?

A: 

I do not believe there is an explicit support for this type of operation. But you can create a good enough solution.

If your service is set to automatic startup then it's safe to assume that the first StartUp is for system startup. Any subsequent startup is a result of the user taking a specific action which caused the service to restart. You can use these two items to build a solution.

Public Class MyService 
  ...
  Private m_first as Boolean = True

  Protected Overrides Sub OnStart(args as String()) 
    If m_first Then
      m_first = False
      Thread.Sleep(TimeSpan.FromMinutes(5))
    End If

    ActuallyStart()
  End Sub
End Class
JaredPar
The only problem with this is that m_first will always be true for most services. When a service is stopped in a single service exe the ServiceBase.Run method returns and the process terminates. When it is next started a new process is launched and a new instance of MyService is run.
Stephen Martin
Also, if you put a Thread.Sleep for 5 minutes in the OnStart method of your service class your service will be considered to have failed to start and be marked as in an error state.
Stephen Martin
+1  A: 

You can look at System.Environment.TickCount to find the time since Windows startup, and if it is lower than 5 minutes, sleep for remaining time.

(Be aware that TickCount may overflow. Use the unmanaged GetTickCount64 API if this is a concern for you.)

oefe
+1  A: 

Why do you need to do this? My guess is that you are trying to work around a dependency problem rather than solve the problem properly.

If you really do need to do this then oefe is on the right track though I would recommend using the System - System Up Time performance counter so as to avoid the integer overflow issue. Also, do not sleep in the OnStart method but rather set a timer to start your work after the appropriate delay or start your work thread immediately and put the delay in the work thread not in the OnStart thread.

Stephen Martin