即使 IIS 空闲,也使后台服务在 IIS 中运行

编程


我正在实现一个后台服务,问题是当我在本地运行它时,它工作正常,因为应用程序已启动并运行。 但是,在 IIS 中,我部署了代码并在 IIS 中启动了服务器。 后台服务在我浏览网站之前不会运行,并且在服务器空闲时变得空闲。

我需要后台服务在我重新启动或启动站点时运行。

我的程序.cs:

C#
builder.Services.AddHostedService<FailedEmailManagmentService>();

我也注册了。

我尝试过的:

C#
using DocumentFormat.OpenXml.InkML;
using DocumentFormat.OpenXml.Office2016.Drawing.ChartDrawing;
using handbook.Controllers.HR;
using handbook.Data;
using handbook.Models.Mail;
using handbook.Repositories.Implementation;
using handbook.Repositories.Interface;
using handbook.ViewModel;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Configuration;
using System.Globalization;
using System.Linq;

namespace handbook.BackgroundmailService
{
    public class EmailReminderSenderService : IHostedService, IDisposable
    {
        public static IConfiguration Configuration { get; set; }
        private Timer _timer;
        private readonly IOauthMailService _emailSender;
        private readonly ILogger<EmailReminderSenderService> _logger;

        public EmailReminderSenderService(IOauthMailService emailSender,
        ILogger<EmailReminderSenderService> logger, 
        IServiceProvider serviceProvider, IConfiguration configuration)
        {
            _emailSender = emailSender;
            _logger = logger;
            Services = serviceProvider;
            Configuration = configuration;
        }

        public IServiceProvider Services { get; }

        private static TimeSpan getJobRunDelay()
        {
            // Change the delay to run every 10 minutes
            return TimeSpan.FromMinutes(1);
        }

        public void Dispose()
        {
            _timer?.Dispose();
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Background service is started");
            _timer = new Timer(SendEmails, null, 
                               getJobRunDelay(), getJobRunDelay());
            return Task.CompletedTask;
        }
public async void SendEmails(object state)
        {
            my task
        }
public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Background service is stopping");
            _timer?.Change(Timeout.Infinite, 0);
            return Task.CompletedTask;
        }
    }
}

解决方案1

コメント

タイトルとURLをコピーしました