I have the following code, which I need to run within an interval of hours, in this case from 9:00 p.m. to 11:59 p.m. every day, to send emails:
public class TimedHostedService : IHostedService, IDisposable
{
private readonly ILogger<TimedHostedService> _logger;
private Timer _timer;
public TimedHostedService(ILogger<TimedHostedService> logger)
{
_logger = logger;
}
public Task StartAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Timed Hosted Service running.");
_timer = new Timer(DoWork, null, TimeSpan.Zero,
TimeSpan.FromHours(1));
return Task.CompletedTask;
}
private void DoWork(object state)
{
TimeSpan start = new TimeSpan(21, 0, 0); //12 am
TimeSpan end = new TimeSpan(23, 59, 0); //4 am
TimeSpan now = DateTime.Now.TimeOfDay;
if ((now > start) && (now < end))//valida dentro del rango de horas
{
SendEmail();
}
}
public void SendEmail(){
......// Code
......
}
}
But the code is executed only once it is published on the server, that is, when checking the next day if the email arrived, which is the SendMail method, I do not have any email, it is as if it was only executed once it is published.
The code is made in .Net Core, and for it to start after publishing it on the server, I must call any method of the controller (which is the only thing I can think of for now, but maybe it could be better and not necessary ).
But what I really need your help is for the process to be executed every day within a defined schedule, since as I told you before, the emails no longer arrive the next day.
Any ideas, in advance, thanks for your attention.
Check this out: IHostedService Stop without any reason
If you are hosting in IIS, you may need to configure your host. If you are hosting in the cloud, it may be easier to use a lambda function.
*Edit: Complementing Brando's answer, try setting the application idle timeout on your app pool like this: