代码改变世界

Hangfire实战(一)------Hangfire+SQL Server实现简单的任务调度

2017-07-29 11:15  神马木牛  阅读(4661)  评论(0编辑  收藏  举报
Hangfire:一个开源的任务调度框架

开发环境:VS2017,SQL Server 2012,.NET Framework 4.5

项目类型:控制台应用程序
1.在vs的程序包控制台中为项目添加Hangfire支持    
PM>Install-Package Hangfire
2.配置sql server连接
GlobalConfiguration.Configuration.UseColouredConsoleLogProvider().UseSqlServerStorage("Data Source=127.0.0.1;User ID=sa;Password=XXXX;Initial Catalog=Hangfire;Connection Reset=False;");
3.创建基本任务
    Hangfire中的任务类型大致有4种类,如图:    
任务类别 任务描述 基本语法
Fire-and-forget 将当前任务放入到一个持久化的队列中,以便程序可以继续执行 BackgroundJob.Enqueue
Delayed 任务在未来的一个时间点执行 BackgroundJob.Schedule
Recurring 可重复执行的任务 RecurringJob.AddOrUpdate
Continuations 将多个任务连接成类似工作流的形式顺序执行 BackgroundJob.ContinueWith
4.创建任务代码参考: 
using (var server = new BackgroundJobServer()) {
    //支持基于队列的任务处理:任务执行不是同步的,而是放到一个持久化队列中,以便马上把请求控制权返回给调用者
    BackgroundJob.Enqueue(() => Console.WriteLine("Simple111"));
    //延迟任务执行:不是马上调用方法,而是设定一个未来时间点再来执行。   
    BackgroundJob.Schedule(() => Console.WriteLine("Reliable!"), TimeSpan.FromSeconds(5));
    //一行代码添加重复执行的任务,其内置了常见的时间循环模式,也可基于CRON表达式来设定复杂的模式。
    RecurringJob.AddOrUpdate(() => Console.WriteLine("Transparent!"), Cron.Minutely);
    //Continuations: Continuations allow you to define complex workflows by chaining multiple background jobs together.
    var jobId = BackgroundJob.Enqueue(() => Test("========First job"));
    BackgroundJob.ContinueWith(jobId, () => Test("========Start execute next task"));          
    Console.WriteLine("Hangfire Server started.Press any key to exit");
    Console.ReadKey();
}
 
5.因为上述任务的存储是利用的Sql server实现,所以任务的运行信息都被保存在了SQL Server中,需要查看对任务的运行状态进行查看,Hangfire也提供了一个可视化的web界面(Dashboard)。查看过程如下:
    1)创建一个ASP.NET项目
    2)添加Hangfire支持
    3)在项目中添加OWIN startup类,然后进行配置
        
    4)启动网站项目,输入http://<your-site>/hangfire ,即可打开如下界面,对任务进行管理
 
 
Referenced: