Search code examples
.net-corewindows-servicesasp.net-core-6.0

.NET Core as Windows Service and service start timeout


We are using simple windows service

        var host = Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration(cfg =>
        {
            cfg.AddConfiguration(Configuration);
            cfg.Build().BindConfigurations();
        })
        .UseSerilog()
        .UseWindowsService()
        .Build();
    host.Run();

This is working great. The issues is that whenever Windows restart, we see the schedular could not start because of this reason,

A timeout was reached (30000 milliseconds) while waiting for the OurScheduler service to connect. 

How can we avoid this error. As this making our choice of .NET Core as background job risky.


Solution

  • I have added a watcher(.bat file) in Task schedular that will make that the job is running if not then start the job,

    @echo off
    for /f "tokens=*" %%a in ('sc query MyWindowsServiceJobName ^| findstr STATE') do set _CmdResult=%%a
    if "%_CmdResult%"=="%_CmdResult:RUNNING=%" (
        SC START MyWindowsServiceJobName
    )