在之前的博客中,介绍过Quartz任务调度框架(Java版本)。最近在.NET平台使用了Quartz任务调度框架,并且结合TopShelf框架,把Quartz发布成Windows Service。
今天把示例贴出来,作为自己学习的记录,如果对读者有所帮助,幸甚至哉!
1.资源
1)Quartz 类库
2)TopShelf/TopShelf.Log4Net
3)Common.Logging/Common.Logging.Core/Common.Logging.Log4Net
2.Jobs
1)FirstJob
using log4net; using Quartz; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QuartzDemo.QuartzJobs { public sealed class FirstJob : IJob { private readonly ILog _logger = LogManager.GetLogger(typeof(FirstJob)); public void Execute(IJobExecutionContext context) { _logger.InfoFormat("FirstJob executed successfully."); } } }2)SecondJob
using log4net; using Quartz; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QuartzDemo.QuartzJobs { public sealed class SecondJob : IJob { private readonly ILog _logger = LogManager.GetLogger(typeof(SecondJob)); public void Execute(IJobExecutionContext context) { _logger.InfoFormat("SecondJob executed successfully."); } } }3.配置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> <!--FirstJob 任务配置--> <job> <name>FirstJob</name> <group>First</group> <description>First Job Test</description> <job-type>QuartzDemo.QuartzJobs.FirstJob,QuartzDemo</job-type> <durable>true</durable> <recover>false</recover> </job> <trigger> <cron> <name>FirstJobTrigger</name> <group>First</group> <job-name>FirstJob</job-name> <job-group>First</job-group> <start-time>2015-01-22T00:00:00+08:00</start-time> <cron-expression>0/5 * * * * ?</cron-expression> </cron> </trigger> <!--SecondJob 任务配置--> <job> <name>SecondJob</name> <group>Second</group> <description>Second Job Test</description> <job-type>QuartzDemo.QuartzJobs.SecondJob,QuartzDemo</job-type> <durable>true</durable> <recover>false</recover> </job> <trigger> <cron> <name>SecondJobTrigger</name> <group>Second</group> <job-name>SecondJob</job-name> <job-group>Second</job-group> <start-time>2015-01-22T00:00:00+08:00</start-time> <cron-expression>0/3 * * * * ?</cron-expression> </cron> </trigger> </schedule> </job-scheduling-data>4.quartz.config
# You can configure your scheduler in either <quartz> configuration section # or in quartz properties file # Configuration section has precedence quartz.scheduler.instanceName = QuartzTest # configure thread pool info quartz.threadPool.type = Quartz.Simpl.SimpleThreadPool, Quartz quartz.threadPool.threadCount = 10 quartz.threadPool.threadPriority = Normal # job initialization plugin handles our xml reading, without it defaults are used quartz.plugin.xml.type = Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz quartz.plugin.xml.fileNames = ~/quartz_jobs.xml # export this server to remoting context #quartz.scheduler.exporter.type = Quartz.Simpl.RemotingSchedulerExporter, Quartz #quartz.scheduler.exporter.port = 555 #quartz.scheduler.exporter.bindName = QuartzScheduler #quartz.scheduler.exporter.channelType = tcp #quartz.scheduler.exporter.channelName = httpQuartz5.TopShelf
服务有启动,停止,继续,暂停等动作,我们使用TopShelf框架很方便地实现。
using Quartz; using Quartz.Impl; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Topshelf; namespace QuartzDemo { public sealed class ServiceRunner : ServiceControl, ServiceSuspend { private readonly IScheduler scheduler; public ServiceRunner() { scheduler = StdSchedulerFactory.GetDefaultScheduler(); } public bool Start(HostControl hostControl) { scheduler.Start(); return true; } public bool Stop(HostControl hostControl) { scheduler.Shutdown(false); return true; } public bool Continue(HostControl hostControl) { scheduler.ResumeAll(); return true; } public bool Pause(HostControl hostControl) { scheduler.PauseAll(); return true; } } }6.Log4Net配置
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <!--日志路径--> <param name= "File" value= "D:\App_Log\servicelog\"/> <!--是否是向文件中追加日志--> <param name= "AppendToFile" value= "true"/> <!--log保留天数--> <param name= "MaxSizeRollBackups" value= "10"/> <!--日志文件名是否是固定不变的--> <param name= "StaticLogFileName" value= "false"/> <!--日志文件名格式为:2008-08-31.log--> <param name= "DatePattern" value= "yyyy-MM-dd".read.log""/> <!--日志根据日期滚动--> <param name= "RollingStyle" value= "Date"/> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n %loggername" /> </layout> </appender> <!-- 控制台前台显示日志 --> <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender"> <mapping> <level value="ERROR" /> <foreColor value="Red, HighIntensity" /> </mapping> <mapping> <level value="Info" /> <foreColor value="Green" /> </mapping> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%n%date{HH:mm:ss,fff} [%-5level] %m" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="Info" /> <param name="LevelMax" value="Fatal" /> </filter> </appender> <root> <!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) --> <level value="all" /> <appender-ref ref="ColoredConsoleAppender"/> <appender-ref ref="RollingLogFileAppender"/> </root> </log4net> </configuration>7.TopShelf启动
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Topshelf; namespace QuartzDemo { class Program { static void Main(string[] args) { var fileInfo = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"); log4net.Config.XmlConfigurator.ConfigureAndWatch(fileInfo); HostFactory.Run(x => { x.RunAsLocalSystem(); x.Service<ServiceRunner>(); x.SetDescription("QuartzDemo服务描述"); x.SetDisplayName("QuartzDemo服务显示名称"); x.SetServiceName("QuartzDemo服务名称"); x.EnablePauseAndContinue(); }); } } }8.效果
安装十分简单,在DOS(系统管理员身份启动)环境下,切换到QuartzDemo.exe所在目录
QuartzDemo.exe install