1、引入dll文件:
nuget控制台:安装quartz:Install-Package Quartz
安装log4net:Install-Package log4net,这里使用log4net记录一些windows服务运行日志,以便查看。
安装完成,会添加4个引用,分别是:Quartz.dll、Common.Logging.dll、Common.Logging.Core.dll、log4net.dll。
2、log4net的相关配置:
config配置:非web项目是在app.config文件中,加入下面代码。注意:configSections节点必须放在最上面,否则会出现‘服务没有响应控制功能’错误,不能启动服务。
非web项目在AssemblyInfo.cs加入(web项目一般在global文件中),log4net的加载配置:
//加载log4配置[assembly:log4net.Config.XmlConfigurator()]
使用时先得到log对象:"ServiceLogger"是配置文件中的logger配置名。
log4net.ILog log = log4net.LogManager.GetLogger("ServiceLogger"); log.Info(DateTime.Now+":定时任务执行");
3、Quartz.Net的配置:
2个文件:quartz.config、quartz_jobs.xml,生成时要选择始终复制。
在线cron生成:http://cron.qqe2.com/
# You can configure your scheduler in eitherconfiguration section# or in quartz properties file# Configuration section has precedencequartz.scheduler.instanceName = ServerScheduler# configure thread pool infoquartz.threadPool.type = Quartz.Simpl.SimpleThreadPool, Quartzquartz.threadPool.threadCount = 10quartz.threadPool.threadPriority = Normal# job initialization plugin handles our xml reading, without it defaults are usedquartz.plugin.xml.type = Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartzquartz.plugin.xml.fileNames = ~/quartz_jobs.xml# export this server to remoting contextquartz.scheduler.exporter.type = Quartz.Simpl.RemotingSchedulerExporter, Quartzquartz.scheduler.exporter.port = 555quartz.scheduler.exporter.bindName = QuartzSchedulerquartz.scheduler.exporter.channelType = tcpquartz.scheduler.exporter.channelName = httpQuartz
true Job demoGroup JobDemo服务描述 WinService.Job,WinService true false JobTrigger JobTriggerGroup Trigger描述 Job demoGroup 0/2 * * * * ?
新建类,实现IJob接口,在Execute方法中写要定时执行的任务代码。
开始与关闭任务:这是在windows服务开始时,同时开始任务的执行。
public partial class ServiceQuartz : ServiceBase { private log4net.ILog log; private ISchedulerFactory schedulerFactory; private IScheduler scheduler; public ServiceQuartz() { InitializeComponent(); log = log4net.LogManager.GetLogger("ServiceLogger"); schedulerFactory = new StdSchedulerFactory(); scheduler = schedulerFactory.GetScheduler(); } protected override void OnStart(string[] args) { log.Info("------------------定时任务已启动------------------------"+DateTime.Now); scheduler.Start(); } protected override void OnStop() { log.Info("-------------------------定时任务被关闭了---------------"+DateTime.Now); scheduler.Shutdown(); } }
4、服务安装与卸载:
cmd要以管理员身份运行
安装:C:\Windows\Microsoft.NET\Framework64\v4.0.30319>InstallUtil.exe D:Project\QuartzTest\WinService\bin\Release\WinService.exe
卸载:sc delete servicequartz