在.Net Core中在一定时间范围内后台运行程序任务

问题描述 投票:0回答:1

我有以下代码,我需要在几个小时内运行它,在本例中是从晚上 9:00 开始。至晚上 11:59每天,发送电子邮件:

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

但是代码只有发布到服务器上后才会执行,即第二天检查电子邮件是否到达时,这是SendMail方法,我没有任何电子邮件,就好像只执行了一次已发布。

代码是在.Net Core中编写的,为了让它在服务器上发布后启动,我必须调用控制器的任何方法(这是我目前唯一能想到的,但也许它可以更好,没有必要)。

但是我真正需要您的帮助的是每天在规定的时间表内执行该流程,因为正如我之前告诉过您的,电子邮件不会在第二天到达。

任何想法,提前感谢您的关注。

c# .net-core timer task timed
1个回答
0
投票

检查一下:IHostedService 无故停止

如果您在 IIS 中托管,您可能需要配置您的主机。如果您在云中托管,那么使用 lambda 函数可能会更容易。

© www.soinside.com 2019 - 2024. All rights reserved.