Quartz.Net为开源的作业调度框架,使用方便,实现IJob接口,及相关配置,即可实现调度。
项目包安装:
install-package Quartz
install-package log4net
install-package Common.Logging.Log4Net1211(最新版为Common.Logging.Log4Net1213,但会出现“Unable to create instance of type Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter.”异常)
配置文件:
编辑App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.2.15.0" newVersion="1.2.15.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
log4net配置文件(log4net.config)
<?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:\QuartzLog\"/>
<!--是否是向文件中追加日志-->
<param name= "AppendToFile" value= "true"/>
<!--log保留天数-->
<param name= "MaxSizeRollBackups" value= ""/>
<!--日志文件名是否是固定不变的-->
<param name= "StaticLogFileName" value= "false"/>
<!--日志文件名格式为:--.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>
quartz配置文件(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 =
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 =
#quartz.scheduler.exporter.bindName = QuartzScheduler
#quartz.scheduler.exporter.channelType = tcp
#quartz.scheduler.exporter.channelName = httpQuartz
job配置信息(quartz_jobs.xml)
<?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> <!--TestJob测试 任务配置-->
<job>
<name>TestJob</name>
<group>Test</group>
<description>TestJob测试</description>
<job-type>ConsoleApplicationQuartz.TestJob,ConsoleApplicationQuartz</job-type>
<durable>true</durable>
<recover>false</recover>
</job>
<trigger>
<cron>
<name>TestJobTrigger</name>
<group>Test</group>
<job-name>TestJob</job-name>
<job-group>Test</job-group>
<start-time>--22T00::+:</start-time>
<cron-expression>/ * * * * ?</cron-expression>
</cron>
</trigger> </schedule>
</job-scheduling-data>
一、控制台项目:
创建Job类实现IJob接口
using log4net;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ConsoleApplicationQuartz
{
public sealed class TestJob : IJob
{
private readonly ILog _logger = LogManager.GetLogger(typeof(TestJob));
public void Execute(IJobExecutionContext context)
{
_logger.InfoFormat("TestJob测试");
}
}
}
Program主程序
using log4net;
using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ConsoleApplicationQuartz
{
class Program
{
static void Main(string[] args)
{
log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config")); ILog log = LogManager.GetLogger(typeof(Program)); StdSchedulerFactory factory = new StdSchedulerFactory();
IScheduler _scheduler = factory.GetScheduler();
_scheduler.Start();
Console.WriteLine("Start..."); Console.Read(); _scheduler.Shutdown();
Console.WriteLine("end...");
Console.Read(); }
}
}
运行效果:
ConsoleApplicationQuartz.TestJob - TestJob测试
ConsoleApplicationQuartz.TestJobname2016-- ::, [QuartzTest_Worker-] INFO ConsoleApplicationQuartz.TestJob - TestJob测试
ConsoleApplicationQuartz.TestJobname2016-- ::, [QuartzTest_Worker-] INFO ConsoleApplicationQuartz.TestJob - TestJob测试
ConsoleApplicationQuartz.TestJobname2016-- ::, [QuartzTest_Worker-] INFO ConsoleApplicationQuartz.TestJob - TestJob测试
ConsoleApplicationQuartz.TestJobname2016-- ::, [QuartzTest_Worker-] INFO ConsoleApplicationQuartz.TestJob - TestJob测试
ConsoleApplicationQuartz.TestJobname2016-- ::, [QuartzTest_Worker-] INFO ConsoleApplicationQuartz.TestJob - TestJob测试
ConsoleApplicationQuartz.TestJobname2016-- ::, [QuartzTest_Worker-] INFO ConsoleApplicationQuartz.TestJob - TestJob测试
ConsoleApplicationQuartz.TestJobname2016-- ::, [QuartzTest_Worker-] INFO ConsoleApplicationQuartz.TestJob - TestJob测试
ConsoleApplicationQuartz.TestJobname2016-- ::, [QuartzTest_Worker-] INFO ConsoleApplicationQuartz.TestJob - TestJob测试
ConsoleApplicationQuartz.TestJobname2016-- ::, [QuartzTest_Worker-] INFO ConsoleApplicationQuartz.TestJob - TestJob测试
ConsoleApplicationQuartz.TestJobname2016-- ::, [] INFO
二、Windows服务程序
创建IJob任务实现类
using log4net;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace FD.ScheduleQuartz.WindowsServiceQuartz
{
public class TestJob : IJob
{
private static readonly ILog Logger = LogManager.GetLogger("TestJob");
public void Execute(IJobExecutionContext context)
{
string jobDes = context.JobDetail.Description;
Logger.Info(jobDes + "运行");
}
}
}
windows服务MainService主服务类
using log4net;
using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks; namespace FD.ScheduleQuartz.WindowsServiceQuartz
{
public partial class MainService : ServiceBase
{
#region 字段
// 日志记录
private readonly ILog _logger;
// 调试器
private readonly IScheduler _scheduler;
#endregion public MainService()
{
InitializeComponent(); log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config")); _logger = LogManager.GetLogger(GetType());
StdSchedulerFactory factory = new StdSchedulerFactory();
_scheduler = factory.GetScheduler();
} protected override void OnStart(string[] args)
{
_scheduler.Start();
_logger.Info("服务启动");
} protected override void OnStop()
{
if (!_scheduler.IsShutdown)
_scheduler.Shutdown();
_logger.Info("服务停止");
} protected override void OnPause()
{
_scheduler.PauseAll();
base.OnPause();
} protected override void OnContinue()
{
_scheduler.ResumeAll();
base.OnContinue();
}
}
}
修改quartz_jobs.xml中配置
将job-type修改为windows服务项目中类型
<job-type>FD.ScheduleQuartz.WindowsServiceQuartz.TestJob,WindowsServiceQuartz</job-type>
创建Windows服务的ProjectInstaller,并设置相应的服务名称及显示名称,运行此服务账号类型(LocalSystem),启动此服务方式和时间设置为Manual
编码后:通过:C:\Windows\Microsoft.NET\Framework64\v4.0.30319\下的installUtil.exe安装Windows服务
如图:
启动服务,及停止服务后,得到log内容:
FD.ScheduleQuartz.WindowsServiceQuartz.MainService - 服务启动
FD.ScheduleQuartz.WindowsServiceQuartz.MainServicename2016-- ::, [QuartzTest_Worker-] INFO TestJob - TestJob测试运行
TestJobname2016-- ::, [QuartzTest_Worker-] INFO TestJob - TestJob测试运行
TestJobname2016-- ::, [QuartzTest_Worker-] INFO TestJob - TestJob测试运行
TestJobname2016-- ::, [QuartzTest_Worker-] INFO TestJob - TestJob测试运行
TestJobname2016-- ::, [QuartzTest_Worker-] INFO TestJob - TestJob测试运行
TestJobname2016-- ::, [QuartzTest_Worker-] INFO TestJob - TestJob测试运行
TestJobname2016-- ::, [QuartzTest_Worker-] INFO TestJob - TestJob测试运行
TestJobname2016-- ::, [QuartzTest_Worker-] INFO TestJob - TestJob测试运行
TestJobname2016-- ::, [QuartzTest_Worker-] INFO TestJob - TestJob测试运行
TestJobname2016-- ::, [QuartzTest_Worker-] INFO TestJob - TestJob测试运行
TestJobname2016-- ::, [QuartzTest_Worker-] INFO TestJob - TestJob测试运行
TestJobname2016-- ::, [] INFO FD.ScheduleQuartz.WindowsServiceQuartz.MainService - 服务停止
FD.ScheduleQuartz.WindowsServiceQuartz.MainServicename