1、新建 ASP.NET Core项目,使用管理NuGet程序包添加Hangfire,然后ASP.NET Core Startup 类中添加如下代码

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Hangfire;namespace MyWebApplication
{public class Startup{public void ConfigureServices(IServiceCollection services){services.AddHangfire(x => x.UseSqlServerStorage("<connection string>"));services.AddHangfireServer();}public void Configure(IApplicationBuilder app){app.UseHangfireDashboard();}}
}

运行以后可以在浏览器中输入http://localhost:5000/hangfire,即运行的地址栏后面加/hangfire,既可以看到效果,如下

全部代码如下:

startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Hangfire;namespace ASP.NETCORETest
{public class Startup{public Startup(IConfiguration configuration){Configuration = configuration;}public IConfiguration Configuration { get; }// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){services.AddRazorPages();//应用程序的入口点和生命周期---应用程序启动起处理的的任务services.AddHostedService<FirstStartService>();services.AddHostedService<SecondStartService>();//Hangfire定时任务services.AddHangfire(a => a.UseSqlServerStorage("Data Source=localhost;Initial Catalog=TestHangfire;Integrated Security=True;"));services.AddHangfireServer();}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime){//应用程序的入口点和生命周期---IHostApplicationLifetime 除了程序进入点外,Host的启动和停止,ASP.NET Core不像ASP.NET MVC用继承的方式捕捉启动及停止事件,//而是透过Startup.Configure注入IHostApplicationLifetime来补捉Application启动停止事件lifetime.ApplicationStarted.Register(async () => await Task.Run(() => Console.WriteLine("IHostApplicationLifetime......Started")));lifetime.ApplicationStopping.Register(async () => await Task.Run(() => Console.WriteLine("IHostApplicationLifetime......Stopping")));lifetime.ApplicationStopped.Register(async () => await Task.Run(() => Console.WriteLine("IHostApplicationLifetime......Stopped")));//停止应用程序var tt = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(a =>{System.Threading.Thread.Sleep(TimeSpan.FromSeconds(100));Console.WriteLine("IHostApplicationLifetime......Stopp---------ing");lifetime.StopApplication();}));tt.Start();if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}else{app.UseExceptionHandler("/Error");}app.UseStaticFiles();app.UseRouting();app.UseAuthorization();//Hangfire定时任务app.UseHangfireDashboard();app.UseEndpoints(endpoints =>{endpoints.MapRazorPages();});}}
}

firststartservice.cs

using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;namespace ASP.NETCORETest
{public class FirstStartService : IHostedService{public async Task StartAsync(CancellationToken cancellationToken){await Task.Run(() => { Console.WriteLine("FirstStartService......StartAsync"); }, cancellationToken);//hangfire定时任务var id = Hangfire.BackgroundJob.Enqueue(() => Console.WriteLine("插入队列的任务"));Hangfire.BackgroundJob.Schedule(() => Console.WriteLine("延迟的任务"), TimeSpan.FromSeconds(5));Hangfire.RecurringJob.AddOrUpdate(() => Console.WriteLine("循环执行的任务"), Hangfire.Cron.Minutely);Hangfire.BackgroundJob.ContinueWith(id, () => Console.WriteLine("指定任务执行之后执行的任务"));}public async Task StopAsync(CancellationToken cancellationToken){await Task.Run(() => { Console.WriteLine("FirstStartService......StopAsync"); }, cancellationToken);}}
}

secondstartservice.cs

using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;namespace ASP.NETCORETest
{public class SecondStartService : IHostedService{public async Task StartAsync(CancellationToken cancellationToken){await Task.Run(() => { Console.WriteLine("SecondStartService......"); }, cancellationToken);}public async Task StopAsync(CancellationToken cancellationToken){await Task.Run(() => { Console.WriteLine("SecondStartService......StopAsync"); }, cancellationToken);}}
}

2、在OWIN Startup 使用如下,可以参考https://blog.csdn.net/LongtengGensSupreme/article/details/107704670?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522162685879516780255232361%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=162685879516780255232361&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_v2~rank_v29-1-107704670.pc_v2_rank_blog_default&utm_term=Hangfire&spm=1018.2226.3001.4450

using Hangfire;
using Microsoft.Owin;
using Owin;[assembly: OwinStartup(typeof(MyWebApplication.Startup))]namespace MyWebApplication
{public class Startup{public void Configuration(IAppBuilder app){GlobalConfiguration.Configuration.UseSqlServerStorage("<name or connection string>");app.UseHangfireDashboard();app.UseHangfireServer();}}
}

ASP.NET Core使用Hangfire做定时任务相关推荐

  1. ASP.NET Core 使用 Hangfire 定时任务

    定时任务组件,除了 Hangfire 外,还有一个 Quarz.NET,不过 Hangfire .NET Core 支持的会更好些. ASP.NET Core 使用 Hangfire 很简单,首先,N ...

  2. 使用ASP.NET Core和Hangfire实现HTTP异步化方案

    Hi,大家好,我是Payne,欢迎大家一如既往地关注我的博客.今天这篇博客里的故事背景,来自我工作中的一次业务对接,因为客户方提供的是长达上百行的XML,所以一度让更喜欢使用JSON的博主感到沮丧,我 ...

  3. Asp.net Core 2.1新功能Generic Host(通用主机)深度学习

    什么是Generic Host ? 这是在Asp.Net Core 2.1加入了一种新的Host,现在2.1版本的Asp.Net Core中,有了两种可用的Host. Web Host –适用于托管W ...

  4. ASP.NET Core Web API + Identity Server 4 + Angular 6 实战小项目视频

    今天开始尝试录制ASP.NET Core Web API的教学视频. 这是一个小项目的实战视频, 该项目采用了: ASP.NET Core 2.1 做API Identity Server 4 Ang ...

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

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

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

    在上一章ASP.NET Core 运行原理解剖[1]:Hosting中,我们介绍了 ASP.NET Core 的启动过程,主要是对 WebHost 源码的探索.而本文则是对上文的一个补充,更加偏向于实 ...

  7. ASP.NET Core+Quartz.Net实现web定时任务

    点击蓝色"Dotnet Plus"关注我哟 加个"星标",每天清晨 07:25,干货推送! 作为一枚后端程序狗,项目实践常遇到定时任务的工作,最容易想到的的思路 ...

  8. Asp.Net Core 入门(一)——Program.cs做了什么

    ASP.NET Core 是微软推出的一种全新的跨平台开源 .NET 框架,用于在 Windows.Mac 或 Linux 上生成基于云的新式 Web 应用程序.国内目前关于Asp.Net Core的 ...

  9. invoke方法是做啥的_使用 NLog 给 Asp.Net Core 做请求监控

    为了减少由于单个请求挂掉而拖垮整站的情况发生,给所有请求做统计是一个不错的解决方法,通过观察哪些请求的耗时比较长,我们就可以找到对应的接口.代码.数据表,做有针对性的优化可以提高效率.在 asp.ne ...

最新文章

  1. 计算机视觉基础:图像处理(上)
  2. 实现将一个字符串转化成对应的整形数字
  3. Codeforces 1196E Connected Component on a Chessboard
  4. Charles调试Https iOS
  5. linux cat 进程,Linux下CAT程序的C实现
  6. Java中interrupted()和isInterrupted()之间的区别
  7. 删库跑路事件发生,SaaS云服务如何守护数据安全
  8. GoCD notes
  9. jq事件不自执行方法
  10. MySQL服务安全加固及防护
  11. 2021-08-12初识maven
  12. hownet与wordnet的区别
  13. 电脑重启只剩下c盘怎么办_win10突然只剩下c盘了怎么办|win10突然只剩下c盘的解决方法...
  14. 博客页面添加动态小人,二次元人物 hexo live2d html人物公仔
  15. java tld文件配置_Java Web应用因tld文件损坏出现的错误
  16. 详解Decorator模式和vistor模式
  17. 因果卷积(causal)与扩展卷积(dilated)
  18. vue获取列表中的数量_vue.js中列表里面的子元素怎么获取列表的索引index值
  19. 2017年大数据可视化机遇,这5大行业不容错过
  20. 计算机网络知识点——4.介质访问控制子层

热门文章

  1. 1062: [NOI2008]糖果雨 - BZOJ
  2. CI持续集成与软件测试
  3. SpringBoot修改启动横幅标语(banner)
  4. 论文阅读【A multi-task attention tree neural net for stance classification and rumor veracity detection】
  5. STM32G0 硬件SPI+DMA+LL库,最高通讯速率32MBit/s
  6. 企业微信批量添加好友
  7. html5代码验证电话号码,这个我觉得挺重要的!
  8. OS学习笔记-5(清华大学慕课)计算机体系结构与内存层次
  9. Windows 安装Docker碰到 cannot enable hyper-v service
  10. 利用mobi 和 epub 电子书文件建立自己的书库