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.