Quartz.Net 学习随手记之02 简单示例

下载Quartz.net 2.1.2,新建控制台应用程序,并添加如下引用

控制台程序代码如下

复制代码
View Code
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using Quartz;
using Quartz.Impl;
using Quartz.Job;

namespace QuartzNET212ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            NameValueCollection properties = new NameValueCollection();

            properties["quartz.scheduler.instanceName"] = "ConsoleScheduler";
            properties["quartz.scheduler.instanceId"] = "instance_one";
            properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
            properties["quartz.threadPool.threadCount"] = "10";
            properties["quartz.threadPool.threadPriority"] = "Normal";
            properties["quartz.jobStore.misfireThreshold"] = "60000";
            properties["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
            properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.StdAdoDelegate, Quartz";
            properties["quartz.jobStore.useProperties"] = "true";
            properties["quartz.jobStore.dataSource"] = "default";
            properties["quartz.jobStore.tablePrefix"] = "QRTZ_";
            properties["quartz.dataSource.default.connectionString"] = "Server=xx.xx.xx.xx;Database=xx;User Id=xx;Password=xx";
            properties["quartz.dataSource.default.provider"] = "SqlServer-20";

            ISchedulerFactory sf = new StdSchedulerFactory(properties);
            IScheduler sched = sf.GetScheduler();

            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.Put("msg", "Hello, this is my first job");

            IJobDetail job = JobBuilder.Create<HelloJob>()
                .WithIdentity("HelloJob", "HelloJobGroup")
                .WithDescription("This is my first job")
                .UsingJobData(jobDataMap)
                .RequestRecovery()
                .Build();

            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("HelloJob", "HelloJobGroup")
                .WithDescription("This is my first trigger")
                .WithCronSchedule("0/5 * * * * ?")//run every 5 seconds
                .Build();

            // Validate that the job doesn't already exists
            if (!sched.CheckExists(job.Key))
            {
                sched.ScheduleJob(job, trigger);
            }

            // Start the scheduler if its in standby
            if (!sched.IsStarted)
            {
                sched.Start();
            }
        }
    }
}
复制代码

对应的作业定义如下

复制代码
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using Quartz;

namespace QuartzNET212ConsoleApp
{
    public class HelloJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            ILog log4net = LogManager.GetLogger(GetType());
            string msg = context.JobDetail.JobDataMap.GetString("msg");
            log4net.Info(msg);
            Console.WriteLine(msg);
        }
    }
}
复制代码

App.config配置文件如下

复制代码
View Code
<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="quartz" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
    <sectionGroup name="common">
      <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging"/>
    </sectionGroup>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>

  <common>
    <logging>
      <factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4net1211">
        <arg key="configType" value="INLINE" />
      </factoryAdapter>
    </logging>
  </common>

  <log4net>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d [%t] %-5p %l - %m%n" />
      </layout>
    </appender>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="ApplicationLog.txt" />
      <appendToFile value="true" />

      <!--Make the rolling file name with the date and size-->
      <rollingStyle value="Composite" />
      <datePattern value="yyyyMM" />
      <maxSizeRollBackups value="100" />
      <maximumFileSize value="2MB" />

      <!--Make the rolling file name like this MyQuartzLog201303.txt, or the deault will be MyQuartzLog.txt201303-->
      <PreserveLogFileNameExtension value="true" />
      <staticLogFileName value="false" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%-5p%d{yyyy-MM-dd hh:mm:ss} – %m%n" />
      </layout>
    </appender>
    <root>
      <level value="INFO" />
      <appender-ref ref="RollingFileAppender" />
    </root>
  </log4net>

</configuration>
复制代码

注意配置文件的版本

产生的Log日志文件如下

数据库中保存的JobDetail和Trigger如下

 为了支持数据库,请自行执行Quartz.Net附带的数据库脚本

posted @   舍长  阅读(1782)  评论(11编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示