How to restart the service when time is reach only once a day

Dani_S 4,501 Reputation points
2024-06-06T10:23:27.6266667+00:00

Hi,

in continue to https://learn.microsoft.com/en-us/answers/questions/1663229/service-monitor

how to restart the service when time is reach only once a day ?

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 } }

Developer technologies | .NET | Other
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2024-06-07T03:12:30.1833333+00:00

    Hi @Dani_S , Welcome to Microsoft Q&A,

    In an infinite loop, check once a minute whether the current time has reached the restart time. If the current time has exceeded the restart time and is within one minute, execute the logic to restart the service. To avoid repeated restarts, wait 24 hours after executing the restart before performing the next check.

    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Logging;
    
    public class TimedHostedService: BackgroundService {
        private readonly IConfiguration _configuration;
        private readonly ILogger <TimedHostedService> _logger;
    
        public TimedHostedService(IConfiguration configuration, ILogger <TimedHostedService> logger) {
            _configuration = configuration;
            _logger = logger;
        }
    
        protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
            while (!stoppingToken.IsCancellationRequested) {
                var restartTime = TimeSpan.Parse(_configuration["ServiceRestartTime"]);
                var currentTime = DateTime.Now.TimeOfDay;
    
                if (currentTime >= restartTime && currentTime < restartTime.Add(TimeSpan.FromMinutes(1))) {
                    _logger.LogInformation($ "Restarting service at {DateTime.Now}");
    
                    // Call the method to restart the service
                    RestartService("YourServiceName");
    
                    _logger.LogInformation($ "Service restarted at {DateTime.Now}");
    
                    // Ensure restarts don't repeat within a day
                    await Task.Delay(TimeSpan.FromHours(24), stoppingToken);
                } else {
                    // Check every minute
                    await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
                }
            }
        }
    }
    

    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.

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,926 Reputation points Volunteer Moderator
    2024-06-06T18:39:24.5933333+00:00

    not sure why you'd schedule a service restart, but it depends on on what you use for a scheduler. you can use Task Scheduler

    https://learn.microsoft.com/en-us/windows/win32/taskschd/task-scheduler-start-page

    it could run your program, or just a simple bat file that just:

    net stop MyService
    net start MyService
    

    if you want to use a second sevice to restart like the sample in the link. you need to add code to detect it ran once that day:

                var restarted = false;
                while (!stoppingToken.IsCancellationRequested)
                {
                    var restartTime = TimeSpan.Parse(_configuration["ServiceRestartTime"]);
                    var currentTime = DateTime.Now.TimeOfDay;
    
                    if (currentTime < restartTime)
                        restarted = false;
                    else if (!restarted)
                    {
                        _logger.LogInformation($"Restarting service at {DateTime.Now}");
    
                        // Restart the service here
                        RestartService("YourServiceName");
    
                        _logger.LogInformation($"Service restarted at {DateTime.Now}");
                        restarted = true;
                    }
    
                    await Task.Delay(60000, stoppingToken); // Check every minute
                }
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.