HangFire任务调度实例(Console和MVC中)及Log4Net日志配置

来源:互联网 发布:mac ladybug试色 编辑:程序博客网 时间:2024/06/06 03:22
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Hangfire{    class Program    {        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);        static void Main(string[] args)        {            GlobalConfiguration.Configuration                .UseLog4NetLogProvider()                .UseSqlServerStorage("Data Source=localhost;User Id=sa;Password=123456;Database=DataSample;Pooling=true;Max Pool Size=5000;Min Pool Size=0;");            Console.WriteLine("Hangfire Server started. Press any key to exit...");            var server = new BackgroundJobServer();            //支持基于队列的任务处理:任务执行不是同步的,而是放到一个持久化队列中,以便马上把请求控制权返回给调用者。            var jobId = BackgroundJob.Enqueue(() => Console.WriteLine("{0}===》这是队列任务!", DateTime.Now.ToString("HH:mm:ss")));            //延迟任务执行:不是马上调用方法,而是设定一个未来时间点再来执行。            BackgroundJob.Schedule(() => Console.WriteLine("{0}===》这是延时任务!", DateTime.Now.ToString("HH:mm:ss")), TimeSpan.FromSeconds(5));            //循环任务执行:一行代码添加重复执行的任务,其内置了常见的时间循环模式,也可基于CRON表达式来设定复杂的模式。            RecurringJob.AddOrUpdate(() => Console.WriteLine("{0}===》这是每分钟执行的任务!", DateTime.Now.ToString("HH:mm:ss")), Cron.Minutely); //注意最小单位是分钟            //延续性任务执行:类似于.NET中的Task,可以在第一个任务执行完之后紧接着再次执行另外的任务            BackgroundJob.ContinueWith(jobId, () => Console.WriteLine("{0}===》这是延续性任务!", DateTime.Now.ToString("HH:mm:ss")));            Console.ReadKey();        }        public static void Send()        {            Console.WriteLine("{0}===》这是队列事务", DateTime.Now.ToString("HH:mm:ss"));        }    }}
<?xml version="1.0" encoding="utf-8" ?><!--App.config--><configuration>  <configSections>    <!--项目的 AssemblyInfo.cs文件上加上[assembly: log4net.Config.XmlConfigurator(Watch = true)]-->    <section name="log4net" type="System.Configuration.IgnoreSectionHandler" />  </configSections>  <log4net>    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender" >      <!--日志文件名开头-->      <file value="C:\\HangFireLog\\" />      <!--是否追加到文件,默认为true,通常无需设置-->      <appendToFile value="true" />      <!--日期的格式,C:\\HangFireLog\\2016-08-08.txt,需设置-->      <datePattern value="yyyy-MM-dd'.txt'" />      <maxSizeRollBackups value="10" />      <rollingStyle value="Date" />      <!--不要使用小数,否则会一直写入当前日志-->      <maximumFileSize value="10MB" />      <staticLogFileName value="false" />      <layout type="log4net.Layout.PatternLayout">        <conversionPattern value="%d [%t] [%-5level] : %message %newline"/>        <!--<param name="ConversionPattern" value="记录时间:%d{yyyy-MM-dd HH:mm:ss}  线程ID:[%thread] 日志级别:%-5level  文件:%file  类:%logger  %message%newline%newline" />-->      </layout>    </appender>    <root>      <!--控制级别,由低到高: ALL|DEBUG|INFO|WARN|ERROR|FATAL|OFF-->      <!--比如定义级别为INFO,则INFO级别向下的级别,比如DEBUG日志将不会被记录-->      <!--如果没有定义LEVEL的值,则缺省为DEBUG-->      <level value="ALL" />      <appender-ref ref="RollingLogFileAppender" />    </root>  </log4net>  <startup>    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />  </startup></configuration>
//MVC中配置和使用 public class DefaultController : Controller{// GET: Defaultpublic ActionResult Index(){    /* 清空数据  HangFire主要数据    TRUNCATE TABLE HangFire.JobQueue    go    TRUNCATE TABLE HangFire.JobParameter    go    TRUNCATE TABLE HangFire.[State]    go    DELETE FROM HangFire.Job    go    */                 MSCL.LogHelper.WriteLog("这是测试");    #region HangFire任务    //支持基于队列的任务处理:任务执行不是同步的,而是放到一个持久化队列中,以便马上把请求控制权返回给调用者。    var jobId = BackgroundJob.Enqueue(() => InsertData("队列任务"));    //延迟任务执行:不是马上调用方法,而是设定一个未来时间点再来执行。    BackgroundJob.Schedule(() => InsertData("延时任务"), TimeSpan.FromSeconds(10));    //循环任务执行:一行代码添加重复执行的任务,其内置了常见的时间循环模式,也可基于CRON表达式来设定复杂的模式。    RecurringJob.AddOrUpdate(() => InsertData("每分钟执行任务"), Cron.Minutely); //注意最小单位是分钟    //延续性任务执行:类似于.NET中的Task,可以在第一个任务执行完之后紧接着再次执行另外的任务    BackgroundJob.ContinueWith(jobId, () => InsertData("连续任务"));    #endregion        return View();}        public static void InsertData(string str)        {            TestTable model = new TestTable();            model.D_Name = string.Format("{0}", str);            model.D_Password = string.Format("{0}密码", str);            model.D_Else = string.Format("{0}其它", str);            DataRootBase.Context.Insert<TestTable>(model);        }}
using System;using System.Threading.Tasks;using Microsoft.Owin;using Owin;using Hangfire;[assembly: OwinStartup(typeof(MVC_demo.Startup))]//Startup.csnamespace MVC_demo{    public class Startup    {        public void Configuration(IAppBuilder app)        {                        GlobalConfiguration.Configuration                .UseSqlServerStorage("Data Source=localhost;User Id=sa;Password=123456;Database=DataSample;Pooling=true;Max Pool Size=5000;Min Pool Size=0;");            BackgroundJob.Enqueue(() => Console.WriteLine("HangFire start"));//初始化生成HangFire数据库表            app.UseHangfireDashboard();            app.UseHangfireServer();        }    }}