周期定时器强制每秒运行



我创建了一个运行在后台服务下的定时定时器

public class PeriodicHostedService : BackgroundService
{
private readonly TimeSpan period = TimeSpan.FromSeconds(1);
private readonly ILogger<PeriodicHostedService> logger;
private readonly IServiceScopeFactory factory;
private int executionCount = 0;
public PeriodicHostedService(ILogger<PeriodicHostedService> logger, IServiceScopeFactory factory)
{
this.logger=logger;
this.factory=factory;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using PeriodicTimer timer = new(period);            
using var scope = factory.CreateScope();
ITimerJob job = scope.ServiceProvider.GetRequiredService<ITimerJob>();
while (
!stoppingToken.IsCancellationRequested &&
await timer.WaitForNextTickAsync(stoppingToken))
{
try
{
await job.ProcessAsync();
executionCount++;
logger.LogInformation($"Executed PeriodicHostedService - Count: {executionCount}");

}
catch (Exception ex)
{
logger.LogInformation($"Failed to execute PeriodicHostedService with exception message {ex.Message}. Good luck next round!");
}
}
}
}

我已经设置了计时器每秒钟运行一次然而,我有工作在计时器需要运行超过1秒只是一个例子

internal class TimerJob : ITimerJob
{
private int runningID;

public async Task  ProcessAsync()
{
runningID++;
Console.WriteLine($"{DateTime.Now} > Current Running ID : {runningID}");
await LongTimeJob();

}
private async Task LongTimeJob ()
{
Console.WriteLine($"{DateTime.Now} > Step1 Async Job End ID : {runningID}");
await Task.Delay(3000).ConfigureAwait(false);
}
}

我能知道如何编写强制每秒钟执行的计时器(并让长期工作继续工作)吗?谢谢你

您可以选择不等待job.ProcessAsync(),这将允许您的代码继续等待下一个tick。

_ = job.ProcessAsync();

我必须承认,每分钟都在运行的作业可能会长时间运行,最终可能会成为一个资源消耗者。你应该检查你的设计是否有任何不必要的副作用。

最新更新