1. 程式人生 > 其它 >ASP.NET Core使用Hangfire做定時任務

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://www.cnblogs.com/1175429393wljblog/p/13407506.html

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();
        }
    }
}
龍騰一族至尊龍騎