AspNetCore2 Hangfire定时任务

Hangfire 是一个简单的用于.net及.net core 应用程序,通过数据库持久化,定时执行后台任务的组件

1、通过NuGet安装Hangfire

2、在Startup.cs文件的ConfigureServices方法里面配置Hangfire服务,设置Hangfire服务使用的数据库

  public void ConfigureServices(IServiceCollection services)
        {
            services.AddHangfire(a => a.UseSqlServerStorage("Data Source=.\SQLExpress;Initial Catalog=Hangfire;User ID=sa;Password=sa"));
            //services.AddMvc();
        }

3、在Configure方法里面加入Hangfire服务和Hangfire的界面控制台

  

  app.UseHangfireServer();
  app.UseHangfireDashboard();

4、运行应用程序,数据库自动生成了相关的表

5、打开http://localhost:port/hangfire,就可以看到Hangfire的控制界面了

 6、在程序启动时添加一个每分钟循环执行的定时任务

  RecurringJob.AddOrUpdate(() =>
                        Console.WriteLine("执行任务了...."), Cron.Minutely());

7、运行程序,在控制台就可以看到刚才加入的定期作业

hangfire的网站:https://www.hangfire.io/

原文地址:https://www.cnblogs.com/tangchun/p/AspNetCore2_Hangfire.html