Skip to content

Instantly share code, notes, and snippets.

@tkouba
Created January 11, 2023 11:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkouba/a72ff7186c828c93da3e4427cffaa980 to your computer and use it in GitHub Desktop.
Save tkouba/a72ff7186c828c93da3e4427cffaa980 to your computer and use it in GitHub Desktop.
Delayed Start Service - helper service for dependent service delayed start
"C:\Windows\Microsoft.Net\Framework\v4.0.30319\csc.exe" /target:exe /out:DelayedStartService.exe /nologo DelayedStartService.cs
using System;
using System.Diagnostics;
using System.ServiceProcess;
class DelayedStartService : ServiceBase
{
private int _delay;
private string[] _services;
public static void Main(string[] args)
{
ServiceBase.Run(new DelayedStartService(args));
}
public DelayedStartService(string[] args)
{
try
{
if (args == null || args.Length == 0 || String.IsNullOrWhiteSpace(args[0]) || !Int32.TryParse(args[0], out _delay))
{
_delay = 120;
}
if (_delay < 0)
_delay = 0;
if (_delay > 120)
_delay = 120;
// Získání seznamu navázaných služeb
if (args != null && args.Length > 1 && !String.IsNullOrWhiteSpace(args[1]))
_services = args[1].Split(',', ';');
else
_services = new string[0];
}
catch (Exception ex)
{
WriteEntry(ex.Message, EventLogEntryType.Error);
}
}
protected override void OnStart(string[] args)
{
WriteEntry(String.Format("Starting delayed service (delay: {0}).", _delay), EventLogEntryType.Information);
try
{
// Čekání _delay sekund
for (int i = 0; i < _delay; i++)
{
this.RequestAdditionalTime(1000);
System.Threading.Thread.Sleep(1000);
}
// Start navázaných služeb
foreach (string service in _services)
{
ServiceController sc = new ServiceController(service);
if (sc.Status != ServiceControllerStatus.Running)
{
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(60));
}
}
}
catch (Exception ex)
{
WriteEntry(ex.Message, EventLogEntryType.Error);
}
WriteEntry("Delayed service started.", EventLogEntryType.Information);
}
protected override void OnStop()
{
WriteEntry("Stoping delayed service.", EventLogEntryType.Information);
try
{
// Stop navázaných služeb
foreach (string service in _services)
{
ServiceController sc = new ServiceController(service);
if (sc.Status != ServiceControllerStatus.Stopped)
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(60));
}
}
}
catch (Exception ex)
{
WriteEntry(ex.Message, EventLogEntryType.Error);
}
}
private void WriteEntry(string message, EventLogEntryType type)
{
try
{
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "DelayedService";
eventLog.WriteEntry(message, type);
}
}
catch (Exception) { /* NOP */ }
}
}
sc create DelayedStartService binPath="\"DelayedStartService.exe\" 90"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment