在 ASP.NET Core 2.1 中, 提供了一个名为 BackgroundService 的类, 在 Microsoft.Extensions.Hosting 命名空间中, 其代码为
- namespace Microsoft.Extensions.Hosting
- {
- //
- // 摘要:
- // Base class for implementing a long running Microsoft.Extensions.Hosting.IHostedService.
- public abstract class BackgroundService : IHostedService, IDisposable
- { protected BackgroundService();
- public virtual void Dispose();
- //
- // 摘要:
- // Triggered when the application host is ready to start the service.
- //
- // 参数:
- // cancellationToken:
- // Indicates that the start process has been aborted.
- public virtual Task StartAsync(CancellationToken cancellationToken);
- //
- // 摘要:
- // Triggered when the application host is performing a graceful shutdown.
- //
- // 参数:
- // cancellationToken:
- // Indicates that the shutdown process should no longer be graceful.
- [AsyncStateMachine(typeof(<StopAsync>d__4))]
- public virtual Task StopAsync(CancellationToken cancellationToken);
- //
- // 摘要:
- // This method is called when the Microsoft.Extensions.Hosting.IHostedService starts.
- // The implementation should return a task that represents the lifetime of the long
- // running operation(s) being performed.
- //
- // 参数:
- // stoppingToken:
- // Triggered when Microsoft.Extensions.Hosting.IHostedService.StopAsync(System.Threading.CancellationToken)
- // is called.
- //
- // 返回结果:
- // A System.Threading.Tasks.Task that represents the long running operations.
- protected abstract Task ExecuteAsync(CancellationToken stoppingToken);
- }
- }
可以看出它是继承自 IHostedService, IDisposable , 而我们只需要继承并实现它的 ExecuteAsync 即可.
也就是说, 我们只需在这个方法内写下这个服务需要做的事,
- internal class TokenRefreshService : BackgroundService
- {
- private readonly ILogger _logger;
- public TokenRefreshService(ILogger<TokenRefresh2Service> logger)
- {
- _logger = logger;
- }
- protected override async Task ExecuteAsync(CancellationToken stoppingToken)
- {
- _logger.LogInformation("Service starting");
- while (!stoppingToken.IsCancellationRequested)
- {
- _logger.LogInformation(DateTime.Now.ToLongTimeString() + ": Refresh Token!");// 在此写需要执行的任务
- await Task.Delay(5000, stoppingToken);
- }
- _logger.LogInformation("Service stopping");
- }
- }
然后在 Startup 中注册服务.
- // This method gets called by the runtime. Use this method to add services to the container.
- public void ConfigureServices(IServiceCollection services)
- {
- services.Configure<CookiePolicyOptions>(options =>
- {
- // This lambda determines whether user consent for non-essential cookies is needed for a given request.
- options.CheckConsentNeeded = context => true;
- options.MinimumSameSitePolicy = SameSiteMode.None;
- });
- services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
- services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, TokenRefreshService>();
- }
注意 注意 注意
1. 当 IIS 上部署的项目启动后, 后台任务随之启动, 任务执行相应的 log 正常输出.
2. 手动回收对应的应用程序池, 任务执行相应的 log 输出停止.
3. 重新请求该网站, 后台任务随之启动, 任务执行相应的 log 重新开始输出.
所以不建议在这样的后台任务中做一些需要固定定时执行的业务处理类的操作, 但对于缓存刷新类的操作还是可以的, 因为当应用程序池回收后再次运行的时候, 后台任务会随着启动.
来源: https://www.cnblogs.com/saodiseng2015/p/9650105.html