Quartz.Net 2.0 bate1 使用
下载后发现在XP下无法使用
安装,编译后找到生成目录在命令行下运行下面的命令进行安装与卸载
按照:> Quartz.Server.exe install
卸载:> Quartz.Server.exe uninstall
说明,需要注意保证开发用的Quartz.dll与windows服务的Quarz.dll是同一个版本的
模块:Quartz.Server中使用topShelf来实现Windows服务的集成
参考:http://www.cnblogs.com/shanyou/archive/2011/05/04/2037008.html
模块:Quartz.Server中使用了Common.Logging作为日志接口,
使用Common.Logging目的是解藕应用程序与log4net,EntLib等日志组件。
参考:http://www.cnblogs.com/wucg/archive/2010/07/26/1784924.html
http://www.cnblogs.com/wdfrog/archive/2010/05/14/1735300.html
Windows事件类型注册工具:
(图1)
(图2)
============下载===============
配置文件示例:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="quartz" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> <sectionGroup name="common"> <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" /> </sectionGroup> </configSections> <connectionStrings> <add name="JL_MFGContext" providerName="System.Data.SqlClient" connectionString="Data Source=192.168.1.7;Initial Catalog=JL_MFG;UID=sa;PWD=xxxx;" /> </connectionStrings> <common> <logging> <factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4net"> <arg key="configType" value="INLINE" /> </factoryAdapter> </logging> </common> <log4net> <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender"> <LogName value="Quartz任务日志" /> <ApplicationName value="Quartz任务日志" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%d [%t] %-5p %l - %m%n" /> </layout> </appender> <appender name="ProductBatchAnalysisLogAppender" type="log4net.Appender.EventLogAppender"> <LogName value="Quartz任务日志" /> <ApplicationName value="成品材料分析" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%d [%t] %-5p %l - %m%n" /> </layout> </appender> <root> <level value="INFO" /> <appender-ref ref="EventLogAppender" /> </root> <logger name="ProductBatchAnalysis" additivity="false"> <level value="DEBUG" /> <appender-ref ref="ProductBatchAnalysisLogAppender" /> </logger> </log4net> <!-- We use quartz.config for this server, you can always use configuration section if you want to. Configuration section has precedence here. --> <!-- <quartz > </quartz> --> </configuration>
上面将Quartz.Server与ProductBatchAnalysis分成了两个事件源"Quartz任务日志"与"成品材料分析",
写入同一个LogName为"Quartz任务日志"的日志文件中(参考上面的图1)
<logger>节点使用additivity="false"来屏蔽root的EventLogAppender的影响(避免一个LogEntity写两次)
实现的IJob代码
[DisallowConcurrentExecution()] public class ProductBatchAnalysis :IJob { private static readonly ILog logger = LogManager.GetLogger(typeof(ProductBatchAnalysis).Name ); //或者GetLogger("ProductBatchAnalysis") private JL_MFGContext _DBCtx; private JL_MFGContext DBCtx { get { if(_DBCtx==null) { _DBCtx=new JL_MFGContext(); } return _DBCtx; } } public void Execute(IJobExecutionContext context) { try { logger.Debug("成品批次分析任务开始"); DBCtx.sim_Log.Add(new sim_Log { AddTime = DateTime.Now, Content = "新加的动动!", ExperimentId = 88 }); DBCtx.SaveChanges(); logger.Debug("成品批次分析任务结束!"); } catch (Exception ex) { logger.Error(ex); #region 抛出错误给Quartz JobExecutionException toThrow = new JobExecutionException(ex); toThrow.RefireImmediately = false; toThrow.UnscheduleFiringTrigger = false; toThrow.UnscheduleAllTriggers = false; throw toThrow; #endregion } } }
Quartz.net Jobs文件配置
<?xml version="1.0" encoding="UTF-8"?> <!-- This file contains job definitions in schema version 2.0 format --> <job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"> <processing-directives> <overwrite-existing-data>true</overwrite-existing-data> </processing-directives> <schedule> <job> <name>ProductBatchAnalysis</name> <group>ProductBatchAnalysis-Group</group> <description>Sample job for Quartz Server</description> <job-type>MFGJobs.ProductBatchAnalysis,MFGJobs</job-type> <durable>true</durable> <recover>false</recover> </job> <trigger> <cron> <name>cronName2</name> <group>cronGroup2</group> <job-name>ProductBatchAnalysis</job-name> <job-group>ProductBatchAnalysis-Group</job-group>
<!-- 使用cron表达公式时应将start-time去掉不然电脑重启后,如果start-time符合要求者任务就会执行一遍 --> <!-- <start-time>1982-06-28T18:15:00+02:00</start-time> --> <cron-expression>0/10 * * ? * *</cron-expression> </cron> </trigger> </schedule> </job-scheduling-data>
注意:使用cron是需要将start-time节点取消掉防止任务在电脑重启后重复执行
上面使用了Cron表达式 ,
参考:http://www.cnblogs.com/wdfrog/archive/2011/06/27/2091404.html
http://www.cnblogs.com/zhangronghua/archive/2009/10/21/1376431.html
文件结构:
使用AdoJobStore
# jobStore setting quartz.jobStore.misfireThreshold = 60000 quartz.jobStore.type = Quartz.Impl.AdoJobStore.JobStoreTX, Quartz quartz.jobStore.useProperties = false quartz.jobStore.dataSource = default quartz.jobStore.tablePrefix = QRTZ_ quartz.jobStore.clustered = true quartz.jobStore.selectWithLockSQL = SELECT * FROM {0}LOCKS UPDLOCK WHERE LOCK_NAME = @lockName quartz.dataSource.default.connectionString = Server=(local);Database=quartz;Trusted_Connection=True quartz.dataSource.default.provider = SqlServer-20
使用参数:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Quartz; using Model.Entities; using Model; using Common.Logging; using MFG.BLL.PMA; namespace MFGJobs { /// <summary> /// 产品批次分析任务 /// </summary> /// [DisallowConcurrentExecution()] [PersistJobDataAfterExecution()] public class ProductBatchAnalysis :IJob { private static readonly ILog logger = LogManager.GetLogger(typeof(ProductBatchAnalysis).Name ); private JL_MFGContext _DBCtx; private JL_MFGContext DBCtx { get { if(_DBCtx==null) { _DBCtx=new JL_MFGContext(); } return _DBCtx; } } public void Execute(IJobExecutionContext context) { try { int offsetDays=0; int days = 1; if(context.JobDetail.JobDataMap.ContainsKey("OffsetDays")) { offsetDays= context.JobDetail.JobDataMap.GetInt("OffsetDays"); } if (context.JobDetail.JobDataMap.ContainsKey("Days")) { days = context.JobDetail.JobDataMap.GetInt("Days"); } DateTime bTime=DateTime.Now.Date.AddDays(offsetDays); DateTime eTime=bTime.AddHours(24*days); logger.InfoFormat("开始,成品批次分析任务,时间段{0}到{1}",bTime,eTime); PMAManager manager = new PMAManager(DBCtx, bTime, eTime); manager.DoResolve(); logger.Info("完成,成品批次分析任务!"); } catch (Exception ex) { logger.Error(ex); #region 抛出错误给Quartz JobExecutionException toThrow = new JobExecutionException(ex); toThrow.RefireImmediately = false; toThrow.UnscheduleFiringTrigger = false; toThrow.UnscheduleAllTriggers = false; throw toThrow; #endregion } } } }
配置文件参考: