之前在公司的一个项目中需要用到定时程序,当时使用的是aspnet core提供的IHostedService接口来实现后台定时程序,具体的示例可去官网查看。现在的dotnet core中默认封装了实现IHostedService接口的基类BackgroundService,该类实现如下:

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System;
using System.Threading;
using System.Threading.Tasks; namespace Microsoft.Extensions.Hosting
{
/// <summary>
/// Base class for implementing a long running <see cref="IHostedService"/>.
/// </summary>
public abstract class BackgroundService : IHostedService, IDisposable
{
private Task _executingTask;
private readonly CancellationTokenSource _stoppingCts = new CancellationTokenSource(); /// <summary>
/// This method is called when the <see cref="IHostedService"/> starts. The implementation should return a task that represents
/// the lifetime of the long running operation(s) being performed.
/// </summary>
/// <param name="stoppingToken">Triggered when <see cref="IHostedService.StopAsync(CancellationToken)"/> is called.</param>
/// <returns>A <see cref="Task"/> that represents the long running operations.</returns>
protected abstract Task ExecuteAsync(CancellationToken stoppingToken); /// <summary>
/// Triggered when the application host is ready to start the service.
/// </summary>
/// <param name="cancellationToken">Indicates that the start process has been aborted.</param>
public virtual Task StartAsync(CancellationToken cancellationToken)
{
// Store the task we're executing
_executingTask = ExecuteAsync(_stoppingCts.Token); // If the task is completed then return it, this will bubble cancellation and failure to the caller
if (_executingTask.IsCompleted)
{
return _executingTask;
} // Otherwise it's running
return Task.CompletedTask;
} /// <summary>
/// Triggered when the application host is performing a graceful shutdown.
/// </summary>
/// <param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param>
public virtual async Task StopAsync(CancellationToken cancellationToken)
{
// Stop called without start
if (_executingTask == null)
{
return;
} try
{
// Signal cancellation to the executing method
_stoppingCts.Cancel();
}
finally
{
// Wait until the task completes or the stop token triggers
await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite, cancellationToken));
} } public virtual void Dispose()
{
_stoppingCts.Cancel();
}
}
}

根据BackgroundService源码,我们只要实现该类的抽象方法ExecuteAsync即可。
可以有两种实现方式来做定时程序,第一种就是实现一个Timer:

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks; namespace DemoOne.Models
{
public class TimedBackgroundService : BackgroundService
{
private readonly ILogger _logger;
private Timer _timer; public TimedBackgroundService(ILogger<TimedBackgroundService> logger)
{
_logger = logger;
} protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds());
_logger.LogInformation("周六!");
return Task.CompletedTask; //Console.WriteLine("MyServiceA is starting."); //stoppingToken.Register(() => File.Create($"E:\\dotnetCore\\Practice\\Practice\\{DateTime.Now.Millisecond}.txt")); //while (!stoppingToken.IsCancellationRequested)
//{
// Console.WriteLine("MyServiceA 开始执行"); // await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); // Console.WriteLine("继续执行");
//} //Console.WriteLine("MyServiceA background task is stopping.");
} private void DoWork(object state)
{
_logger.LogInformation($"Hello World! - {DateTime.Now}");
} public override void Dispose()
{
base.Dispose();
_timer?.Dispose();
}
}
}

我们看看StartAsync的源码。上面的实现方式会直接返回一个已完成的Task,这样就会直接运行StartAsync方法的if判断,那么如果我们不走if呢?那么就应该由StartAsync方法返回一个已完成的Task.
第二个即是:

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks; namespace DemoOne.Models
{
public class TimedBackgroundService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Console.WriteLine("MyServiceA is starting."); stoppingToken.Register(() => File.Create($"E:\\dotnetCore\\Practice\\Practice\\{DateTime.Now.Millisecond}.txt")); while (!stoppingToken.IsCancellationRequested)
{
Console.WriteLine("MyServiceA 开始执行"); await Task.Delay(TimeSpan.FromSeconds(), stoppingToken); Console.WriteLine("继续执行");
} Console.WriteLine("MyServiceA background task is stopping.");
} public override void Dispose()
{
base.Dispose();
}
}
}

最后我们将实现了BackgroundService的类注入到DI即可:
services.AddHostedService<TimedBackgroundService>();

dotnet core的Microsoft.Extensions.Hosting 组件中,充斥着类似IHostedService接口中定义的方法:StartAsync、StopAsync方法。我们注入的HostedService服务会在WebHost类中通过GetRequiredService获取到注入的定时服务。随后执行StartAsync方法开始执行。建议看看Hosting组件源码,会有很多的收获。

aspnet core运行后台任务的更多相关文章

  1. Core开发-后台任务利器Hangfire使用

    Core开发-后台任务利器Hangfire使用 ASP.NET Core开发系列之后台任务利器Hangfire 使用. Hangfire 是一款强大的.NET开源后台任务利器,无需Windows服务/ ...

  2. ASP.NET Core 运行原理解剖[2]:Hosting补充之配置介绍

    在上一章中,我们介绍了 ASP.NET Core 的启动过程,主要是对 WebHost 源码的探索.而本文则是对上文的一个补充,更加偏向于实战,详细的介绍一下我们在实际开发中需要对 Hosting 做 ...

  3. ASP.NET Core 运行原理解剖[5]:Authentication

    在现代应用程序中,认证已不再是简单的将用户凭证保存在浏览器中,而要适应多种场景,如App,WebAPI,第三方登录等等.在 ASP.NET 4.x 时代的Windows认证和Forms认证已无法满足现 ...

  4. AspNet Core 初步认识

    Core 的出现对我我没有很大的影响,当时在Core要发布的时候听到周围的人再聊再谈,我没有去太多关注,就是一个屌丝开发人员. 直到又一次偶然见到一位特别喜欢.net的老开发人员谈起Core时落泪了, ...

  5. AspNet Core Api Restful +Swagger 发布IIS 实现微服务之旅 (二)

    上一步我们创建好CoreApi 接下来在框架中加入 Swagger  并发布  到 IIS (1)首先点击依赖项>管理Nuget包 (2)输入 Swashbuckle.aspnetCore  比 ...

  6. AspNet Core Api Restful +Swagger 发布IIS

    上一步我们创建好CoreApi 接下来在框架中加入 Swagger  并发布  到 IIS (1)首先点击依赖项>管理Nuget包 (2)输入 Swashbuckle.aspnetCore  比 ...

  7. Cookies 初识 Dotnetspider EF 6.x、EF Core实现dynamic动态查询和EF Core注入多个上下文实例池你知道有什么问题? EntityFramework Core 运行dotnet ef命令迁移背后本质是什么?(EF Core迁移原理)

    Cookies   1.创建HttpCookies Cookie=new HttpCookies("CookieName");2.添加内容Cookie.Values.Add(&qu ...

  8. 设计模式(一)单例模式:创建模式 ASPNET CORE WEB 应用程序的启动 当项目中 没有STARTUP.CS 类如何设置启动 配置等等

    设计模式(一)单例模式:创建模式 先聊一下关于设计的几个原则(1)单一原则(SRP):一个类应该仅有一个引起它变化的原因 :意思就是 (一个类,最好只负责一件事情,并且只有一个引起它变化的原因(2)开 ...

  9. ASPNETCOREAPI 跨域处理 SQL 语句拼接 多条件分页查询 ASPNET CORE 核心 通过依赖注入(注入服务)

    ASPNETCOREAPI 跨域处理 AspNetCoreApi 跨域处理 如果咱们有处理过MV5 跨域问题这个问题也不大. (1)为什么会出现跨域问题:  浏览器安全限制了前端脚本跨站点的访问资源, ...

随机推荐

  1. 【JVM】JVM内存结构 VS Java内存模型 VS Java对象模型

    原文:JVM内存结构 VS Java内存模型 VS Java对象模型 Java作为一种面向对象的,跨平台语言,其对象.内存等一直是比较难的知识点.而且很多概念的名称看起来又那么相似,很多人会傻傻分不清 ...

  2. CentOS7使用firewalld防火墙配置端口

    安装启用firewalld防火墙 CentOS7默认的防火墙是firewalld 如果没有firewalld防火墙,可以执行yum install firewalld 命令进行安装 firewalld ...

  3. 洛谷P3369 普通平衡树

    刚学平衡树,分别用了Splay和fhq-treap交了一遍. 这是Splay的板子,貌似比较短? Splay #include <iostream> #include <cstdio ...

  4. 如何将JPG格式的图片转换成PNG格式

    study from : https://jingyan.baidu.com/article/6079ad0e63a4fc28ff86db37.html

  5. Gym - 101350A Sherlock Bones(思维)

    The great dog detective Sherlock Bones is on the verge of a new discovery. But for this problem, he ...

  6. Python中查看函数相关文档

    1.dir查看对象属性 >>> dir(set) ['__and__', '__class__', '__contains__', '__delattr__', '__dir__', ...

  7. Hadoop基础-镜像文件(fsimage)和编辑日志(edits)

    Hadoop基础-镜像文件(fsimage)和编辑日志(edits) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.查看日志镜像文件(如:fsimage_00000000000 ...

  8. DirectX11 With Windows SDK--08 Direct2D与Direct3D互操作性以及利用DWrite显示文字

    前言 注意:从这一章起到后面的所有项目无一例外都利用了Direct2D与Direct3D互操作性,但系统要求为Win10, Win8.x 或 Win7 SP1且安装了KB2670838补丁以支持Dir ...

  9. 新年 flag

    在浮躁的年代本不该如此贪多,奈何鸭梨山大...温故知新吧 GO中文社区 深入学习一两门新的编程语言: -Go编程基础 -Go Web基础 -Go名库讲解 rustlang 中文文档 知乎板块 GO 知 ...

  10. [再寄小读者之数学篇](2014-06-21 Beal-Kaot-Majda type logarithmic Sobolev inequality)

    For $f\in H^s(\bbR^3)$ with $s>\cfrac{3}{2}$, we have $$\bex \sen{f}_{L^\infty}\leq C\sex{1+\sen{ ...