Service Monitor

Dani_S 2,846 Reputation points
2024-05-05T16:07:58.2833333+00:00

Hi,

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,

.NET
.NET
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
    2024-05-06T08:53:13.42+00:00

    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
                        RestartService("YourServiceName");
    
                        _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.Stop();
                        sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30));
                        sc.Start();
                        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.SetBasePath(Directory.GetCurrentDirectory());
                        config.AddJsonFile("appsettings.json", optional: false);
                    })
                    .ConfigureServices((hostContext, services) =>
                    {
                        services.AddHostedService<Worker>();
                    })
                    .ConfigureLogging((hostingContext, logging) =>
                    {
                        logging.AddConsole();
                    });
    
                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,

    Jiale


    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