Quartz.net使用记录

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节点必须放在最上面,否则会出现‘服务没有响应控制功能’错误,不能启动服务。

<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net debug="false">
    <!-- OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL -->
    <!-- Print only messages of level DEBUG or above in the packages -->
    <logger name="ServiceLogger">
      <level value="INFO" />
      <appender-ref ref="SysAppender" />
    </logger>

    <appender name="SysAppender" type="log4net.Appender.RollingFileAppender,log4net">
      <param name="File" value="log/" />
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="&quot;Logs_&quot;yyyyMMdd&quot;.txt&quot;" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
        <param name="Header" value="&#xD;&#xA;----------------------header--------------------------&#xD;&#xA;" />
        <param name="Footer" value="&#xD;&#xA;----------------------footer--------------------------&#xD;&#xA;" />
      </layout>
    </appender>
  </log4net>

  非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 either <quartz> configuration section
# or in quartz properties file
# Configuration section has precedence

quartz.scheduler.instanceName = ServerScheduler

# 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 = httpQuartz
<?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>Job</name>
      <group>demoGroup</group>
      <description>JobDemo服务描述</description>
      <job-type>WinService.Job,WinService</job-type>
      <durable>true</durable>
      <recover>false</recover>
    </job>

    <trigger>
      <cron>
        <name>JobTrigger</name>
        <group>JobTriggerGroup</group>
        <description>Trigger描述</description>
        <job-name>Job</job-name>
        <job-group>demoGroup</job-group>
        <cron-expression>0/2 * * * * ?</cron-expression>
      </cron>
    </trigger>
  </schedule>
</job-scheduling-data>

  新建类,实现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

posted @ 2016-04-20 14:52  随缘梦中人  阅读(554)  评论(0编辑  收藏  举报