Hangfire入门(任务调度)

一、简介

    英文官网:http://hangfire.io/

    开源地址:https://github.com/HangfireIO

    Hangfire 不依赖于具体的.NET应用类型,包含.NET 和.NET Core。

    Hangfire 是一款强大的.NET开源后台任务利器,无需Windows服务/任务计划程序。

    可以使用于ASP.NET 应用也可以使用于控制台。Hangfire 只需简单几句代码即可创建新的不同种类的任务。

二、使用条件

    1. .NET Framework 4.5

    2. 持久存储(SQL Azure, SQL Server 2008 R2及以上版本,Redis 

    3. Newtonsoft.Json 版本 ≥ 5.0.1

三、安装使用

   1. 创建一个控制台项目,使用NuGet 命令行安装,选择对应的项目

   2. PM> Install-Package Hangfire ,安装会有一段时间,耐心等待

   3. 安装好后就可以在Main方法中使用了

   

class Program
    {
        static void Main(string[] args)
        {
            GlobalConfiguration.Configuration
               .UseColouredConsoleLogProvider()
               .UseSqlServerStorage("Server=.;User ID=sa;Password=123456;database=xxxx;Connection Reset=False;");

            //支持基于队列的任务处理:任务执行不是同步的,而是放到一个持久化队列中,以便马上把请求控制权返回给调用者。
          //   BackgroundJob.Enqueue(() => Console.WriteLine("Simple!"));
            //延迟任务执行:不是马上调用方法,而是设定一个未来时间点再来执行。            
           //  BackgroundJob.Schedule(() => Console.WriteLine("Reliable!"), TimeSpan.FromSeconds(5));
            //循环任务执行:一行代码添加重复执行的任务,其内置了常见的时间循环模式,也可基于CRON表达式来设定复杂的模式。
           // RecurringJob.AddOrUpdate(() => Console.WriteLine("Transparent!"), Cron.Minutely);//注意最小单位是分钟
             
            using (var server = new BackgroundJobServer())
            {
                BackgroundJob.Enqueue(() => Console.WriteLine("Simple111"));

                Console.WriteLine("Hangfire Server started. Press any key to exit...");
                Console.ReadKey();

            }
        }
    }

 

    

参考文章:

http://www.cnblogs.com/redmoon/p/4394962.html

http://www.cnblogs.com/huangchenqin/p/5210448.html

 http://codeopinion.com/background-tasks/

posted @ 2016-12-23 23:18  心存善念  阅读(4130)  评论(0编辑  收藏  举报