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


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 完整代碼:

 

public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddHangfire(r=>r.UseSqlServerStorage("Data Source=.;Initial Catalog=HangfireDemo;User ID=sa;Password=123456"));
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//GlobalConfiguration.Configuration.UseSqlServerStorage("Data Source=.;Initial Catalog=OrchardCMS;User ID=sa;Password=sa123456");

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

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");
});
});


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


 

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


免責聲明!

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



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