后台服务未在iis windows server上启动发布的.net core,

8e2ybdfx  于 2023-04-21  发布在  Windows
关注(0)|答案(1)|浏览(174)

我有一个后台服务,它通过使用库NCrontab在特定时间作为作业工作我的项目使用。net 7这是我的后台服务

public class GenerateSiteMapXMLFileBackgroundService : BackgroundService, IHostedService
    {
        private CrontabSchedule _schedule;
        private DateTime _nextRun;
        public IServiceScopeFactory _serviceScopeFactory;

        private string Schedule => "00 20 00 * * *"; //Runs every day at 00:20:00 (cron expression) {ss mm hh dd mm yy}
        public GenerateSiteMapXMLFileBackgroundService(IServiceScopeFactory serviceScopeFactory, IServiceProvider services)
        {
            _schedule = CrontabSchedule.Parse(Schedule, new CrontabSchedule.ParseOptions { IncludingSeconds = true });
            _nextRun = _schedule.GetNextOccurrence(DateTime.Now);
            _serviceScopeFactory = serviceScopeFactory;
            Services = services;
        }
        public IServiceProvider Services { get; }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            using (var scope = Services.CreateScope())
            {
                var scoped = scope.ServiceProvider.GetRequiredService<ISiteMapeService>();
                do
                {
                    var now = DateTime.Now;
                    if (now > _nextRun)
                    {
                        await scoped.CreateSiteMapFile();
                        _nextRun = _schedule.GetNextOccurrence(DateTime.Now);
                    }
                    await Task.Delay(5000, stoppingToken); //5 seconds delay
                }
                while (!stoppingToken.IsCancellationRequested);
            }
        }
    }

我已经在startup.js中注册了

services.AddHostedService<GenerateSiteMapXMLFileBackgroundService>();

当我在本地测试它并设置我想要的时间时,它运行良好并启动,但当我在iis服务器上发布我的项目时,它不工作。
我猜有一些配置我必须做的iis服务器,但我不知道

g0czyy6m

g0czyy6m1#

默认情况下,IIS将在一段时间不活动后关闭应用程序池。如果不配置IIS,后台工作进程将无法按预期工作。

## IIS WebAdmin Module
Import-Module WebAdministration

$AppPoolInstance = Get-Item IIS:\AppPools\$AppPool

Write-Output "Set Site PreLoadEnabled to true"
Set-ItemProperty IIS:\Sites\$Site -name applicationDefaults.preloadEnabled -value True

Write-Output "Set Recycling.periodicRestart.time  = 0"
$AppPoolInstance.Recycling.periodicRestart.time = [TimeSpan]::Parse("0");
$AppPoolInstance | Set-Item

Write-Output "Set App Pool start up mode to AlwaysRunning"
$AppPoolInstance.startMode = "alwaysrunning"

Write-Output "Disable App Pool Idle Timeout"
$AppPoolInstance.processModel.idleTimeout = [TimeSpan]::FromMinutes(0)
$AppPoolInstance | Set-Item

if ($appPoolStatus -ne "Started") {
    Write-Output "Starting App Pool"
    Start-WebAppPool $AppPool    
} else {
    Write-Output "Restarting App Pool"
    Restart-WebAppPool $AppPool
}

或者,如果您更喜欢GUI,则只需在IIS中编辑设置。
Credit

相关问题