之前聊过如何在.net core 中添加后台服务,
当时使用的是BackgroundService的形式,这里使用IHostedService接口
namespace oneModelMultiTable.BackgroundService
{public class EllisTest : IHostedService, IDisposable{private readonly ILogger<EllisTest> _logger;private Timer _timer;public EllisTest(ILogger<EllisTest> logger){_logger = logger;}public void Dispose(){_timer?.Dispose();}public Task StartAsync(CancellationToken cancellationToken){_logger.LogInformation("start service");_timer = new Timer(Refresh, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));return Task.CompletedTask;}public Task StopAsync(CancellationToken cancellationToken){_logger.LogInformation("stop service");return Task.CompletedTask;}public void Refresh(object state){_logger.LogInformation(DateTime.Now.ToString() + "测试定时任务");}}
}
builder.Services.AddHostedService<EllisTest>();
StartAsync应该限于短时间运行的任务,因为托管服务是顺序运行的,并且在StartAsync运行完成之前不会启动其他服务。
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-7.0&tabs=visual-studio