Service Monitor

Dani_S 2,846 Reputation points


I want a worker service with config file of time when to restart a given service.

In the config file will be the time.

the service will run always and when time reach check if service is running

to restart it.

Thanks in advance,

Microsoft Technologies based on the .NET software framework.
3,438 questions
{count} votes

Accepted answer
  1. Jiale Xue - MSFT 34,671 Reputation points Microsoft Vendor

    Hi @Dani_S , Welcome to Microsoft Q&A,

    You can use the System.ServiceProcess.ServiceController class to stop and start services.

    Here's how you can create a worker service that reads a time from a configuration file and restarts a given service when that time is reached:

    First, install the System.ServiceProcess.ServiceController NuGet package:

    dotnet add package System.ServiceProcess.ServiceController --version 5.0.0

    Then, create the worker service:

    using System;
    using System.IO;
    using System.ServiceProcess;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Logging;
    namespace ServiceRestartWorker
        public class Worker : BackgroundService
            private readonly ILogger<Worker> _logger;
            private readonly IConfiguration _configuration;
            public Worker(ILogger<Worker> logger, IConfiguration configuration)
                _logger = logger;
                _configuration = configuration;
            protected override async Task ExecuteAsync(CancellationToken stoppingToken)
                while (!stoppingToken.IsCancellationRequested)
                    var restartTime = TimeSpan.Parse(_configuration["ServiceRestartTime"]);
                    var currentTime = DateTime.Now.TimeOfDay;
                    if (currentTime >= restartTime)
                        _logger.LogInformation($"Restarting service at {DateTime.Now}");
                        // Restart the service here
                        _logger.LogInformation($"Service restarted at {DateTime.Now}");
                    await Task.Delay(60000, stoppingToken); // Check every minute
            private void RestartService(string serviceName)
                using (var sc = new ServiceController(serviceName))
                    if (sc.Status == ServiceControllerStatus.Running)
                        sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30));
                        sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30));
        public class Program
            public static async Task Main(string[] args)
                var builder = new HostBuilder()
                    .ConfigureAppConfiguration((hostingContext, config) =>
                        config.AddJsonFile("appsettings.json", optional: false);
                    .ConfigureServices((hostContext, services) =>
                    .ConfigureLogging((hostingContext, logging) =>
                await builder.RunConsoleAsync();

    Make sure to replace "YourServiceName" with the name of the service you want to restart.

    In this version, the worker service continuously checks the current time against the time specified in the configuration file. When the current time is equal to or greater than the restart time, it restarts the service specified.

    Best Regards,


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful