Quartz.NET 3.x 例子

2018-03-25 3262点热度 0条评论

最近写项目需要用到定时任务,所以就找到了Quartz.NET,但网上的例子都是到处抄袭的,完全没有适合Quartz.NET 3.x 的有用信息,这里就将自己的使用例子帖一下。

  • IDE:VS2017
  • .Net : 4.5.2

写在前面

Quartz.NET 在3.x已经将插件分离了,所以如果要从xml直接加载文件,需要引入插件包

引入包

配置

app.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <configSections>
    <section name="quartz" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </configSections>

  <quartz>
    <add key="quartz.scheduler.instanceName" value="QuartzScheduler"/>
    <add key="quartz.threadPool.type" value="Quartz.Simpl.SimpleThreadPool, Quartz"/>
    <add key="quartz.threadPool.threadCount" value="10"/>
    <!--******************************Plugin配置*********************************************-->
    <add key="quartz.plugin.jobInitializer.type" value="Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz.Plugins"/>
    <add key="quartz.plugin.jobInitializer.fileNames" value="quartz_jobs.xml"/>
  </quartz>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
  </startup>

</configuration>

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>

    <!--开始执行一个调度-->
    <job>
      <name>jldwjob</name>
      <group>kelun</group>
      <description>计量单位</description>
      <job-type>Kelun.JldwJob, Kelun</job-type><!--格式:实现了IJob接口的包含完整命名空间的类名,程序集名称-->
      <durable>true</durable>
      <recover>false</recover>
    </job>
    
    <trigger>
      <cron>
        <name>jlwd</name>
        <group>kelun</group>
        <job-name>jldwjob</job-name>
        <job-group>kelun</job-group>
        <!--<start-time>2018-01-22T00:00:00+08:00</start-time>-->
        <cron-expression>0/1 * * * * ?</cron-expression><!--每3秒执行一次-->
      </cron>
    </trigger>

  </schedule>
</job-scheduling-data>

接口实现

using Kelun.Log4Net;
using Quartz;
using System.Reflection;
using System.Threading.Tasks;

namespace Kelun
{
    class JldwJob : IJob
    {

        private static readonly IMyLog Logger = MyLogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public Task Execute(IJobExecutionContext context)
        {
            return Task.Run(() => 
            {
                Logger.Info("定时任务执行");
            });
        }
    }
}

启动Quartz

public MainForm()
{
    InitializeComponent();
    RunProgramAsync().GetAwaiter().GetResult();
}

private static async Task RunProgramAsync()
{
    try
    {
        StdSchedulerFactory factory = new StdSchedulerFactory();

        IScheduler scheduler = await factory.GetScheduler();

        //开启调度器
        await scheduler.Start();

        //创建一个作业
        //IJobDetail job = JobBuilder.Create<JldwJob>().WithIdentity("myJob", "group1").Build();

        //ITrigger trigger = TriggerBuilder.Create()
        //    .WithIdentity("myTrigger", "group1")
        //    .StartNow()     //现在开始
        //    .WithSimpleSchedule(x => x
        //        .WithIntervalInSeconds(1)   //触发时间,1秒一次
        //        .RepeatForever())
        //    .Build();

        //把作业,触发器加入调度器。
       //await scheduler.ScheduleJob(job, trigger);  

        //await scheduler.Shutdown();

    }
    catch (SchedulerException se)
    {
        Logger.Error("执行错误", se);
    }
}

禁用Quartz.NET日志输出

<logger name="Quartz">
	<level value="OFF" />
</logger>

Jalena

原创内容,转载请注明出处! 部分内容来自网络,请遵守法律适用!

文章评论