ASP.NET Core使用Hangfire做定时任务
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做定时任务的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 集成框架 -- 快手接入
- 下一篇: Pandas DataFrame 使用技