zoukankan      html  css  js  c++  java
  • Hangfire实战(一)------Hangfire+SQL Server实现简单的任务调度

    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:
  • 相关阅读:
    C# 时间格式化
    下载好证书后,手机无法安装fiddler证书
    charles抓包步骤整理
    Windows 8的本地化应用程序清单
    代码滑动panorama-即程序中设置SelectedIndex
    WP7开发 Sqlite数据库的使用 解决Unable open the database
    mybatis plus eq and or
    弹出窗口
    父子窗口传递参数
    从后台数据库查询的List数据怎么在前台combobox显示
  • 原文地址:https://www.cnblogs.com/lightmao/p/7254197.html
Copyright © 2011-2022 走看看