ASP.NET Core開發-后台任務利器Hangfire使用


ASP.NET Core開發系列之后台任務利器Hangfire 使用。

Hangfire 是一款強大的.NET開源后台任務利器,無需Windows服務/任務計划程序。

可以使用於ASP.NET 應用也可以使用於控制台。Hangfire 只需簡單幾句代碼即可創建新的不同種類的任務。

目前 Hangfire 已經支持.NET Core ,現在就給大家講解下在ASP.NET Core 里的使用。

Hangfire GitHub:https://github.com/HangfireIO/Hangfire

官網:http://hangfire.io/ 

相關文檔介紹:http://docs.hangfire.io/en/latest/

 

首先我們新建一個ASP.NET Core Web Application

選擇模板-》空的模板

然后添加引用:

NuGet 命令行執行

Install-Package Hangfire

 

添加好引用以后我們就可以來使用。

打開Startup.cs

首先在ConfigureServices 方法中注冊服務:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHangfire(r=>r.UseSqlServerStorage("Data Source=.;Initial Catalog=HangfireDemo;User ID=sa;Password=123456"));
        }

這里是配置數據庫,數據庫需要確保存在,這里配置的是SQL Server數據庫,目前官方支持SQL Server。

然后在Configure 方法中加入HangfireServer及HangfireDashboard:

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

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

            app.Run(context =>
            {
                return context.Response.WriteAsync("Hello from ASP.NET Core!");
            });
        }

 

然后選擇Kestrel執行,訪問地址:http://localhost:5000/hangfire

成功運行,下面我們就可以來添加任務了。

            app.Map("/index", r =>
            {
                r.Run(context =>
                {
                    //任務每分鍾執行一次
                    RecurringJob.AddOrUpdate(() => Console.WriteLine($"ASP.NET Core LineZero"), Cron.Minutely());
                    return context.Response.WriteAsync("ok");
                });
            });

            app.Map("/one", r =>
            {
                r.Run(context =>
                {
                    //任務執行一次
                    BackgroundJob.Enqueue(() => Console.WriteLine($"ASP.NET Core One Start LineZero{DateTime.Now}"));
                    return context.Response.WriteAsync("ok");
                });
            });

            app.Map("/await", r =>
            {
                r.Run(context =>
                {
                    //任務延時兩分鍾執行
                    BackgroundJob.Schedule(() => Console.WriteLine($"ASP.NET Core await LineZero{DateTime.Now}"), TimeSpan.FromMinutes(2));
                    return context.Response.WriteAsync("ok");
                });
            });

這里創建任務只是為了方便,我們也可以在初始化的時候創建,也可以在controller 中創建。 

下面我們來執行。

首先訪問 http://localhost:5000/index

然后訪問 http://localhost:5000/await

最后訪問 http://localhost:5000/one

這樣任務也就都執行起來了。

Jobs 也就是查看所有的任務,我們可以在節目界面操作運行及刪除,很方便。

我們還可以點擊任務,查看任務詳情。以及任務執行結果。

 

最終運行一段時間,還有圖表展示

 

Startup.cs 完整代碼:

 1     public class Startup
 2     {
 3         // This method gets called by the runtime. Use this method to add services to the container.
 4         // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
 5         public void ConfigureServices(IServiceCollection services)
 6         {
 7             services.AddHangfire(r=>r.UseSqlServerStorage("Data Source=.;Initial Catalog=HangfireDemo;User ID=sa;Password=123456"));
 8         }
 9 
10         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
11         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
12         {
13             loggerFactory.AddConsole();
14 
15             if (env.IsDevelopment())
16             {
17                 app.UseDeveloperExceptionPage();
18             }
19            
20 
21             app.UseHangfireServer();
22             app.UseHangfireDashboard();
23 
24             app.Map("/index", r =>
25             {
26                 r.Run(context =>
27                 {
28                     //任務每分鍾執行一次
29                     RecurringJob.AddOrUpdate(() => Console.WriteLine($"ASP.NET Core LineZero"), Cron.Minutely());
30                     return context.Response.WriteAsync("ok");
31                 });
32             });
33 
34             app.Map("/one", r =>
35             {
36                 r.Run(context =>
37                 {
38                     //任務執行一次
39                     BackgroundJob.Enqueue(() => Console.WriteLine($"ASP.NET Core One Start LineZero{DateTime.Now}"));
40                     return context.Response.WriteAsync("ok");
41                 });
42             });
43 
44             app.Map("/await", r =>
45             {
46                 r.Run(context =>
47                 {
48                     //任務延時兩分鍾執行
49                     BackgroundJob.Schedule(() => Console.WriteLine($"ASP.NET Core await LineZero{DateTime.Now}"), TimeSpan.FromMinutes(2));
50                     return context.Response.WriteAsync("ok");
51                 });
52             });
53 
54 
55             app.Run(context =>
56             {
57                 return context.Response.WriteAsync("Hello from ASP.NET Core!");
58             });
59         }
60     }
View Code

 

通過Hangfire, 這樣我們就可以很方便的在ASP.NET Core 里創建后台任務。而且提供管理界面供我們操作。

 

如果你覺得本文對你有幫助,請點擊“推薦”,謝謝。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM