ASP.NET Core开发-后台任务利器Hangfire使用

SP.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

ASP.NET Core开发-后台任务利器Hangfire使用_第1张图片

成功运行,下面我们就可以来添加任务了。

复制代码

            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

这样任务也就都执行起来了。

ASP.NET Core开发-后台任务利器Hangfire使用_第2张图片

Jobs 也就是查看所有的任务,我们可以在节目界面操作运行及删除,很方便。

我们还可以点击任务,查看任务详情。以及任务执行结果。

ASP.NET Core开发-后台任务利器Hangfire使用_第3张图片

最终运行一段时间,还有图表展示

ASP.NET Core开发-后台任务利器Hangfire使用_第4张图片

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     }

复制代码

通过Hangfire, 这样我们就可以很方便的在ASP.NET Core 里创建后台任务。而且提供管理界面供我们操作。

 后台常用任务调度创建和使用:

注意:WriteLog是自己封装的一个通用记录日志的方法!

复制代码

//支持基于队列的任务处理:任务执行不是同步的,而是放到一个持久化队列中,以便马上把请求控制权返回给调用者。
var jobId = BackgroundJob.Enqueue(()=>WriteLog("队列任务执行了!"));

//延迟任务执行:不是马上调用方法,而是设定一个未来时间点再来执行,延迟作业仅执行一次
var jobId = BackgroundJob.Schedule(()=>WriteLog("一天后的延迟任务执行了!"),TimeSpan .FromDays(1));//一天后执行该任务

//循环任务执行:一行代码添加重复执行的任务,其内置了常见的时间循环模式,也可基于CRON表达式来设定复杂的模式。【用的比较的多】
RecurringJob.AddOrUpdate(()=>WriteLog("每分钟执行任务!"), Cron.Minutely); //注意最小单位是分钟

//延续性任务执行:类似于.NET中的Task,可以在第一个任务执行完之后紧接着再次执行另外的任务
BackgroundJob.ContinueWith(jobId,()=>WriteLog("连续任务!"));

 注意,周期性使用可以使用Cron表达式。

# ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of the month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12)
# │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday;
# │ │ │ │ │                                   7 is also Sunday on some systems)
# │ │ │ │ │
# │ │ │ │ │
# * * * * * command to execute

Entry Description Equivalent to
@yearly (or @annually) 每年1月3号2:01分运行 1 2 3 1 *
@monthly 每月3号2:01分运行 1 2 3 * *
@weekly 每周日的2:01分运行 1 2 * * 0
@daily 每天的2:01分运行 1 2 * * *
@hourly 每小时的1分运行 1 * * * *
@reboot Run at startup N/A
 

博客示例代码GitHub:https://github.com/linezero/Blog

Hangfire相关使用学习资料:

官网地址:https://www.hangfire.io/

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

中文文档:https://www.bookstack.cn/read/Hangfire-zh-official/README.md 

GitHub使用示例源码:https://github.com/HangfireIO/Hangfire.Samples(包括控制台应用程序,window服务,ASP.NET MVC,WebForm)

Hangfire使用文章汇总:https://www.bbsmax.com/R/xl56E0nrJr/

https://www.cnblogs.com/owenzh/p/11623869.html

你可能感兴趣的:(Core,asp.net,c#,数据库)