c#之 quartz的学习

  目录:

    一. Quartz的API

    二.Trigger 的使用

    三.使用 JobDataMap 来往Job中传值

    四. Calendars 

    五.SimpleTrigger

    六.CronTrigger

 

一. Quartz的API

  • IScheduler - 与 scheduler 进行交互的主要接口
  • IJob - 你希望被 scheduler 执行的组件的接口
  • IJobDetail - 用于定义 Jobs 实例
  • ITrigger - 定义将会在scheduler上执行的 job 上的组件
  • JobBuilder - 用于定义或建立(define/build) JobDetail 实例,JobDetail定义了Jobs实例
  • TriggerBuilder - 用于定义或建立 Trigger 实例

可以对照 这一篇 quartz 的代码来印证

 

二.Trigger 的使用

// define the job and tie it to our HelloJob class
    IJobDetail job = JobBuilder.Create<HelloJob>()
        .WithIdentity("myJob", "group1") // name "myJob", group "group1"
        .Build();
        
    // Trigger the job to run now, and then every 40 seconds
    ITrigger trigger = TriggerBuilder.Create()
        .WithIdentity("myTrigger", "group1")
        .StartNow()
        .WithSimpleSchedule(x => x
            .WithIntervalInSeconds(40)
            .RepeatForever())            
        .Build();
        
    // Tell quartz to schedule the job using our trigger
    await sched.scheduleJob(job, trigger);

这里除了 WithSimpleSchedule 扩展方法,还有如下:

  • WithCalendarIntervalSchedule
  • WithCronSchedule
  • WithDailyTimeIntervalSchedule
  • WithSimpleSchedule

 

三.使用 JobDataMap 来往Job中传值

在JobDataMap中设置值

// define the job and tie it to our DumbJob class
IJobDetail job = JobBuilder.Create<DumbJob>()
    .WithIdentity("myJob", "group1") // name "myJob", group "group1"
    .UsingJobData("jobSays", "Hello World!")
    .UsingJobData("myFloatValue", 3.141f)
    .Build();

从JobDataMap中获取值

public class DumbJob : IJob
{
    public async Task Execute(IJobExecutionContext context)
    {
        JobKey key = context.JobDetail.Key;

        JobDataMap dataMap = context.JobDetail.JobDataMap;

        string jobSays = dataMap.GetString("jobSays");
        float myFloatValue = dataMap.GetFloat("myFloatValue");

        await Console.Error.WriteLineAsync("Instance " + key + " of DumbJob says: " + jobSays + ", and val is: " + myFloatValue);
    }
}

 

还有从 JobExecutionContext’s merged JobDataMap 中获取值的方式

public class DumbJob : IJob
{
    public async Task Execute(IJobExecutionContext context)
    {
        JobKey key = context.JobDetail.Key;

        JobDataMap dataMap = context.MergedJobDataMap;  // Note the difference from the previous example

        string jobSays = dataMap.GetString("jobSays");
        float myFloatValue = dataMap.GetFloat("myFloatValue");
        IList<DateTimeOffset> state = (IList<DateTimeOffset>)dataMap["myStateData"];
        state.Add(DateTimeOffset.UtcNow);

        await Console.Error.WriteLineAsync("Instance " + key + " of DumbJob says: " + jobSays + ", and val is: " + myFloatValue);
    }
}

或者,可以通过注入 data map 的值到类中

public class DumbJob : IJob
{
    public string JobSays { private get; set; }
    public float FloatValue { private get; set; }

    public async Task Execute(IJobExecutionContext context)
    {
        JobKey key = context.JobDetail.Key;

        JobDataMap dataMap = context.MergedJobDataMap;  // Note the difference from the previous example

        IList<DateTimeOffset> state = (IList<DateTimeOffset>)dataMap["myStateData"];
        state.Add(DateTimeOffset.UtcNow);

        await Console.Error.WriteLineAsync("Instance " + key + " of DumbJob says: " + JobSays + ", and val is: " + FloatValue);
    }
}

 

四. Calendars 

ICalendar 接口

namespace Quartz
{
    public interface ICalendar
    {
        string Description { get; set; }

        ICalendar CalendarBase { set; get; }

        bool IsTimeIncluded(DateTimeOffset timeUtc);

        DateTime GetNextIncludedTimeUtc(DateTimeOffset timeUtc);

        ICalendar Clone();
    }
} 

 

示例:

    HolidayCalendar cal = new HolidayCalendar();
    cal.AddExcludedDate(someDate);
    
    await sched.AddCalendar("myHolidays", cal, false);
    
    ITrigger t = TriggerBuilder.Create()
        .WithIdentity("myTrigger")
        .ForJob("myJob")
        .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(9, 30)) // execute job daily at 9:30 每天9:30执行
        .ModifiedByCalendar("myHolidays") // but not on holidays 不包含假期
        .Build();

    // .. schedule job with trigger

    ITrigger t2 = TriggerBuilder.Create()
        .WithIdentity("myTrigger2")
        .ForJob("myJob2")
        .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(11, 30)) // execute job daily at 11:30
        .ModifiedByCalendar("myHolidays") // but not on holidays
        .Build();
    
    // .. schedule job with trigger2 

 

用来在日历上的某一段时间不必执行任务时,可以使用这种方式

 

五.SimpleTrigger

这里列举一些Simple Trigger 的使用示例

 

1.建立一个在某个时间点的触发器,不重复执行

// trigger builder creates simple trigger by default, actually an ITrigger is returned
ISimpleTrigger trigger = (ISimpleTrigger) TriggerBuilder.Create()
    .WithIdentity("trigger1", "group1")
    .StartAt(myStartTime) // some Date 
    .ForJob("job1", "group1") // identify job with name, group strings
    .Build();

2.建立一个某个时间点的触发器,并且每10秒执行一次,执行10次

trigger = TriggerBuilder.Create()
    .WithIdentity("trigger3", "group1")
    .StartAt(myTimeToStartFiring) // if a start time is not given (if this line were omitted), "now" is implied
    .WithSimpleSchedule(x => x
        .WithIntervalInSeconds(10)
        .WithRepeatCount(10)) // note that 10 repeats will give a total of 11 firings
    .ForJob(myJob) // identify job with handle to its JobDetail itself                   
    .Build();

3.建立一个触发器,在之后每5分钟执行一次

trigger = (ISimpleTrigger) TriggerBuilder.Create()
    .WithIdentity("trigger5", "group1")
    .StartAt(DateBuilder.FutureDate(5, IntervalUnit.Minute)) // use DateBuilder to create a date in the future
    .ForJob(myJobKey) // identify job with its JobKey
    .Build();

4.建立一个触发器,每5分钟执行一次,知道22:00

trigger = TriggerBuilder.Create()
    .WithIdentity("trigger7", "group1")
    .WithSimpleSchedule(x => x
        .WithIntervalInMinutes(5)
        .RepeatForever())
    .EndAt(DateBuilder.DateOf(22, 0, 0))
    .Build();

5.建立一个触发器,将在下一个整点执行,每2个小时执行一次

trigger = TriggerBuilder.Create()
    .WithIdentity("trigger8") // because group is not specified, "trigger8" will be in the default group
    .StartAt(DateBuilder.EvenHourDate(null)) // get the next even-hour (minutes and seconds zero ("00:00"))
    .WithSimpleSchedule(x => x
        .WithIntervalInHours(2)
        .RepeatForever())
    // note that in this example, 'forJob(..)' is not called 
    //  - which is valid if the trigger is passed to the scheduler along with the job  
    .Build();

await scheduler.scheduleJob(trigger, job);

 

六.CronTrigger

 

CronExpression 用于配置CronTrigger 的实例,Cron-Expression 是一个由7个 sub-expression 组成的字符串,

这7个 sub-expression 由空格分隔开,代表的含义:

  1. Seconds
  2. Minutes
  3. Hours
  4. Day-of-Month
  5. Month
  6. Day-of-Week
  7. Year (optional field)

这里的1-7个,每个都是一个field ;

 

例如: “0 0 12 ? * WED”  表示每个周三的12点

 

1.单独的 sub-expression 可以包含 ranges and/or (即某个范围,与,或) ,

  例如前面的 week 属性 的WED,可以替换为 “MON-FRI” ,  “MON, WED, FRI” ,   “MON-WED,SAT” 

2.通配符可以被用来表示可能的值,因此前面例子中的 Month 处的 * ,意味着每个月;而 Day-of-Month 处如果使用 * ,表示 这周的每天

3.所有的field 都有一个有效值的集合可被指定。

  •  seconds and minutes:0-59
  •  hours : 0-23
  • Day-of-Month :  0-31 ,但是这个地方,你需要根据每个月有多少天来进行给值
  • Months : 0-11 或者用JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV ,DEC
  • Days-of-Week : 0-7 (1=Sunday) 或者 SUN, MON, TUE, WED, THU, FRI and SAT 

4. / 符号,可以用来指定值的增量。例如 0/15 表示在Minutes field 处,它意味着每15分钟,从0分钟开始;如果 ‘3/20’ ,表示在Minutes field 处,每20分钟,从3分钟处开始;

5.? 符号,用于day-of-month 和 day-of-week 处。用于指定没有特定值。当你需要在这两个field中的其中一个指定值,而另一个不指定时,是有用的;

6. L 符号,用在 day-of-month 和 day-of-week 处。这个符号是 last 的缩写,在两个不同的field (指day-of-month 和day-of-week )有不同的含义。

  例如,

  L 用在day-of-month处意味着月份的最后一个天;

  L单独用在day-of-week 处,表示 7 或者 SAT ,

  但是如果用在另一个值的后面,则意味着 the last xxx day of the month ,

  例如,6L或者FRIL 这两个都意味着 the last friday of the month 即这个月的最后一个周五;

  当使用L时,不要指定 lists 或者范围值,因为你将得到令人困惑的结果。

7.W 符号,指定最接近给定日期的周(星期)。例如,当你在 day-of-month 处指定15W时,意味着最接近这个月15号的周(星期)。

8. # 符号,指定月份的第几个周(星期),例如, 在day-of-week 处的 6#3 或者 FRI#3 意味着月份的第三个周五

 

下面是一些使用示例

1>.每5分钟执行一次

  "0 0/5 * * * ?"

2>.每5分钟,并且这分钟的10秒开始执行(i.e. 10:00:10 am, 10:05:10 am, etc

  "10 0/5 * * * ?"

3>.每周三和周五的10:30,11:30,12:30,13:30 执行

"  0 30 10-13 ? * WED,FRI"

4>.在每个月的5号和20号,在8点和10点之间,每30分钟执行一次(10:00不执行,在8:00,8:30,9:00,9:30 执行)

  "0 0/30 8-9 5,20 * ?"

 

建立CronTriggers

在每天上午8:00到17:00之间,每隔1秒执行一次

trigger = TriggerBuilder.Create()
    .WithIdentity("trigger3", "group1")
    .WithCronSchedule("0 0/2 8-17 * * ?")
    .ForJob("myJob", "group1")
    .Build();

在每天10:42am执行

// we use CronScheduleBuilder's static helper methods here
trigger = TriggerBuilder.Create()
    .WithIdentity("trigger3", "group1")
    .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(10, 42))
    .ForJob(myJobKey)
    .Build();

或者

trigger = TriggerBuilder.Create()
    .WithIdentity("trigger3", "group1")
    .WithCronSchedule("0 42 10 * * ?")
    .ForJob("myJob", "group1")
    .Build();

 

建立一个触发器,在每周三10:42执行,并且指定一个TimeZone而不是系统默认的

trigger = TriggerBuilder.Create()
    .WithIdentity("trigger3", "group1")
    .WithSchedule(CronScheduleBuilder
        .WeeklyOnDayAndHourAndMinute(DayOfWeek.Wednesday, 10, 42)
        .InTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Central America Standard Time")))
    .ForJob(myJobKey)
    .Build();

trigger = TriggerBuilder.Create()
    .WithIdentity("trigger3", "group1")
    .WithCronSchedule("0 42 10 ? * WED", x => x
        .InTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Central America Standard Time")))
    .ForJob(myJobKey)
    .Build();

 

还有一些监听的listener 等其他知识,这里没讲,

可以参考网址

https://www.quartz-scheduler.net/documentation/quartz-3.x/tutorial/index.html

posted @ 2019-05-21 23:55  Vincent-yuan  阅读(7308)  评论(0编辑  收藏  举报