Search code examples
c#windowsservicewindows-server-2003windows-xp-sp3

How can I delay my created service in Windows Server 2003 & Windows XP?


I made a service (WinServiceProject) many days ago and I want that this start automatic but with a Delayed Time... I found a solution but this cant help me: http://support.microsoft.com/kb/193888/en-us

I modify the regedit at HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WinServiceProject but this doesn't work.

I add Multi-String Value (DependOnService) and set many services before... this works but dont like I want.

The solution I need its with time, set many time and execute the service after this time. If I need add code to my service I will do it.

Thanks.


Solution

  • I resolve the problem with this code!!

    public static void RestartService(string serviceName, int timeoutMilliseconds)

        {
    
            ServiceController service = new ServiceController(serviceName);
    
            try
            {
                int millisec1 = Environment.TickCount;
                TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
    
                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
    
                // count the rest of the timeout
                //int millisec2 = Environment.TickCount;
                timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - millisec1);
    
                service.Start();
                service.WaitForStatus(ServiceControllerStatus.Running, timeout);
            }
    
            catch
            {
                // ...
            }
    
        }