Run a program task in the background within a time range in .Net Core

119 views Asked by At

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.

Edit: Should I configure the downtime? enter image description here

2

There are 2 answers

1
balti On

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:

  1. Go into the IIS Manager
  2. Click on Application Pools (on the left)
  3. Right click on your app pool
  4. Select "Set Application Pool Defaults..."
  5. Change the value of "Idle Time-out (minutes)" from 20 to 0
0
Brando Zhang On

Yes, you should modify the idle time-out value from 20 minutes to 0. If you don't set it, it will terminate it after 20 minutes if there is not any other request sent to the application.

Like below:

enter image description here