• 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();
            }
        }
    }
    龙腾一族至尊龙骑
  • 相关阅读:
    java跳过构造方法新建对象
    java实现类似qq的窗口对聊
    NoSql的产生
    C语言跳出循环
    C语言for循环
    C语言while语句
    C语言条件运算符
    C语言switch语句
    C语言逻辑运算符
    C语言关系运算符
  • 原文地址:https://www.cnblogs.com/1175429393wljblog/p/15040408.html
Copyright © 2020-2023  润新知