采用Windows服務任務調度Quartz.NET


     Windows服務使用標准的Csharp編寫,任務調度框架采用開源的Quartz.NET。
    首先創建Windows服務-JobService
    圖片

    其次創建類庫項目-JobLibrary
    整體解決方案架構圖如下:
    圖片

    在JobLibary中添加Quartz.NET的Nuget包引用,添加之后,vs會自動添加一系列的依賴項,這些依賴項是必須的,別手抖刪掉了。
    圖片
    
    其次再添加Common.Logging.Log4Net1211的Nuget包,他是Log4net的另外一種實現,會自動添加log4net的依賴
    所有添加的包如下圖:
    
圖片

  下面開始添加任務,在libary中添加一個job類繼承IJob,並實現其接口

  

using System;
using Quartz;

namespace JobLibrary
{
    public class Job : IJob
    {
        private static readonly Common.Logging.ILog logger = Common.Logging.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                logger.Info("job開始");
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter("E:\\log.txt", true))
                {
                    sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + " 吃飯---睡覺");

                }
                logger.Info("job結束"); 
            }
            catch (Exception e)
            {
                logger.Error(e.Message);
            }
        }
    }   
    
}

這個類就是你需要做的任務。我的任務是吃飯和睡覺。

然后再在JobService中添加JobLibrary的引用,並且添加如下代碼(需要同樣添加Nuget引用)

using Common.Logging;
using Quartz;
using Quartz.Impl;
using System.ServiceProcess;

namespace JobService
{
    public partial class Service1 : ServiceBase
    {
        private IScheduler scheduler;
        private readonly ILog logger;
        public Service1()
        {
            InitializeComponent();
            ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
            scheduler = schedulerFactory.GetScheduler();
            logger = LogManager.GetLogger(GetType());
        }

        protected override void OnStart(string[] args)
        {
            logger.Info("Quartz服務成功啟動");
            scheduler.Start();
        }

        protected override void OnStop()
        {
            scheduler.Shutdown(false);
        }
    }
}

  

代碼完成之后,需要配置quartz_jobs.xml,在JobService項目添加xml配置文件“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>
    <!--定義示例任務1 Job-->
    <job>
      <name>DemoJob1</name>
      <group>DeomJobGroup</group>
      <description>Quartz.Net示例任務1</description>
      <job-type>JobLibrary.Job,JobLibrary</job-type>
      <durable>true</durable>
      <recover>false</recover>
    </job>
 

    <!--定義示例任務1 觸發器 每10秒執行一次DemoJob1任務-->
    <trigger>
      <cron>
        <name>DemoJob1Trigger</name>
        <group>DeomJobTriggerGroup</group>
        <job-name>DemoJob1</job-name>
        <job-group>DeomJobGroup</job-group>
        <cron-expression>0/10 * * * * ?</cron-expression>
      </cron>
    </trigger>
  </schedule>
</job-scheduling-data>

  這個配置文件有個莫名其妙的bug,就是最上面那幾行不能有空行,不知道是什么情況,有知道伙計望告知。被這個坑了半天。

  其次,在添加quartz.config配置文件

  

# 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

然后就是app.config的quartz的配置了

  

 <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>

  然后就是編譯,記住quartz_jobs.xml和quartz.config這兩個文件一定要編譯輸出,要不然讀取不到。

 

  

啟動之后,就可以看到寫到文件中的內容了。

如果一台機器上跑任務,那么如果這太機器掛掉了怎么辦?如果是多台機器上跑任務,那么任務重復執行怎么辦?

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM