Quartz2.2.X定时任务调度(基础篇)

相关文摘

quartz官网:http://www.quartz-scheduler.org/
quartz官网Examples教程:http://www.quartz-scheduler.org/documentation/quartz-2.2.x/examples/
quartz官网源码与Examples例子:https://github.com/Huangdongrong/quartz
quartz概念:http://student-lp.iteye.com/blog/2093395
quartz基本概念及原理:https://www.ibm.com/developerworks/cn/opensource/os-cn-quartz/

添加quartz依赖包

本文例子以maven项目实现,在pom文件添加quartz的依赖

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.2.1</version>
</dependency>

实现简单的触发器SimpleTrigger

  • 实现简单的触发器定时任务主要几点:
    1. 初始化SchedulerFactory
    2. 获取Scheduler实例
    3. 创建Job任务
    4. 创建触发器SimpleTrigger,并设置触发器规则
    5. 告诉quartz,job绑定SimpleTrigger触发器
    6. 启动调度,定时工作
  • SimpleTrigger例子
  1. 创建Job任务

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    package test;
    import org.quartz.Job;
    import org.quartz.JobExecutionContext;
    import org.quartz.JobExecutionException;
    import java.util.Date;
    /**
    * Created by Donie on 2016/8/17.
    */
    public class SimpleQuartzJob implements Job {
    public SimpleQuartzJob() {}
    public void execute(JobExecutionContext context) throws JobExecutionException {
    System.out.println("In SimpleQuartzJob - executing its JOB at "
    + new Date() + " by " + context.getTrigger().getKey());
    }
    }
  2. 简单的触发器实例

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    package test;
    import org.quartz.*;
    import org.quartz.impl.StdSchedulerFactory;
    import java.util.Date;
    import static org.quartz.JobBuilder.newJob;
    import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
    import static org.quartz.TriggerBuilder.newTrigger;
    /**
    * Created by Donie on 2016/8/17.
    */
    public class SimpleTriggerTest {
    public static void main(String[] args) throws SchedulerException {
    //初始化一个Schedule工厂
    SchedulerFactory schedulerFactory = new StdSchedulerFactory();
    //通过schedule工厂类获得一个Scheduler类,通过SchedulerFactory获取一个调度器实例
    Scheduler scheduler = schedulerFactory.getScheduler();
    //如Job名字、描述、关联监听器等信息,JobDetail承担了这一角色,JobDetail要求指定Job的实现类,以及任务在Scheduler中的组名和Job名称
    JobDetail job = newJob(SimpleQuartzJob.class).withIdentity("job1", "group1").build();
    // 在当前时间1秒后运行
    Date startTime = DateBuilder.nextGivenSecondDate(null, 1);
    //主要有SimpleTrigger和CronTrigger这两个子类。当仅需触发一次或者以固定时间间隔周期执行,SimpleTrigger是最适合的选择
    // repeatSecondlyForever(1) 每秒执行一次,repeatHourlyForever(1)每小时执行一次,,withIntervalInMinutes(1).withRepeatCount(20)每间隔1分钟执行一次,总共直到执行20次
    SimpleTrigger simpleTrigger = (SimpleTrigger) newTrigger().withIdentity("simpleTrigger1", "group1").startAt(startTime).withSchedule(simpleSchedule().withIntervalInMinutes(1).withRepeatCount(100)).build();
    // scheduler代表一个Quartz的独立运行容器,Trigger和JobDetail可以注册到Scheduler中,两者在Scheduler中拥有各自的组及名称,组及名称是Scheduler查找定位容器中某一对象的依据,
    // Trigger的组及名称必须唯一,JobDetail的组和名称也必须唯一(但可以和Trigger的组和名称相同,因为它们是不同类型的)。
    // Scheduler定义了多个接口方法,允许外部通过组及名称访问和控制容器中Trigger和JobDetail。
    // Scheduler可以将Trigger绑定到某一JobDetail中,这样当Trigger触发时,对应的Job就被执行。一个Job可以对应多个Trigger,但一个Trigger只能对应一个Job。
    // 可以通过SchedulerFactory创建一个Scheduler实例。Scheduler拥有一个SchedulerContext,它类似于ServletContext,保存着Scheduler上下文信息,Job和Trigger都可以访问SchedulerContext内的信息。
    // SchedulerContext内部通过一个Map,以键值对的方式维护这些上下文数据,SchedulerContext为保存和获取数据提供了多个put()和getXxx()的方法。可以通过Scheduler# getContext()获取对应的SchedulerContext实例;
    // Tell quartz to schedule the job using our simpleTrigger
    scheduler.scheduleJob(job, simpleTrigger);
    // 调度启动
    scheduler.start();
    // try {
    // //1分钟
    // Thread.sleep(600L * 1000L);
    //
    // } catch (Exception e) {
    // }
    //
    // //调度器停止
    // scheduler.shutdown(true);
    //
    // // 显示一下 已经执行的任务信息
    // SchedulerMetaData metaData = scheduler.getMetaData();
    // System.out.println("~~~~~~~~~~ 执行了 " + metaData.getNumberOfJobsExecuted() + " 个 jobs.");
    // //scheduler.shutdown(false);
    }
    }

实现定时触发器CronTrigger

  • 实现定时触发器CronTrigger定时任务主要几点:
    1. 初始化SchedulerFactory
    2. 获取Scheduler实例
    3. 创建Job任务
    4. 创建触发器CronTrigger,并设置触发器规则
    5. 告诉quartz,job绑定SimpleTrigger触发器
    6. 启动调度,定时工作
  • CronTrigger例子
  1. 创建Job任务

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    package test;
    import org.quartz.Job;
    import org.quartz.JobExecutionContext;
    import org.quartz.JobExecutionException;
    import java.util.Date;
    /**
    * Created by Donie on 2016/8/17.
    */
    public class SimpleQuartzJob implements Job {
    public SimpleQuartzJob() {}
    public void execute(JobExecutionContext context) throws JobExecutionException {
    System.out.println("In SimpleQuartzJob - executing its JOB at "
    + new Date() + " by " + context.getTrigger().getKey());
    }
    }
  2. CronTrigger实例

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    package test;
    import org.quartz.*;
    import org.quartz.impl.StdSchedulerFactory;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import java.util.Date;
    import static org.quartz.CronScheduleBuilder.cronSchedule;
    import static org.quartz.JobBuilder.newJob;
    import static org.quartz.TriggerBuilder.newTrigger;
    /**
    * Created by Donie on 2016/8/24.
    */
    public class CronTriggerTest {
    public void run() throws Exception {
    Logger log = LoggerFactory.getLogger(CronTriggerTest.class);
    //初始化一个Schedule工厂
    SchedulerFactory sf = new StdSchedulerFactory();
    //通过schedule工厂类获得一个Scheduler类
    Scheduler sched = sf.getScheduler();
    //通过设置job name, job group, and executable job class初始化一个JobDetail
    JobDetail job = newJob(SimpleQuartzJob.class).withIdentity("job1", "group1").build();
    //设置触发器名称和触发器所属的组名初始化一个定时触发器 ,并设置定时器的触发规则,每20执行一次
    CronTrigger trigger = newTrigger().withIdentity("trigger1", "group1").withSchedule(cronSchedule("0/20 * * * * ?")).build();
    //交给调度器调度运行JobDetail和Trigger
    Date ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: "
    + trigger.getCronExpression());
    // job 2 will run every other minute (at 15 seconds past the minute) 将每隔一分钟(在过去的15秒)执行一次
    job = newJob(SimpleQuartzJob.class).withIdentity("job2", "group1").build();
    trigger = newTrigger().withIdentity("trigger2", "group1").withSchedule(cronSchedule("15 0/2 * * * ?")).build();
    ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: "
    + trigger.getCronExpression());
    // job 3 will run every other minute but only between 8am and 5pm 将每一分钟但只在上午8点到下午5点执行一次
    job = newJob(SimpleQuartzJob.class).withIdentity("job3", "group1").build();
    trigger = newTrigger().withIdentity("trigger3", "group1").withSchedule(cronSchedule("0 0/2 8-17 * * ?")).build();
    ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: "
    + trigger.getCronExpression());
    // job 4 will run every three minutes but only between 5pm and 11pm 将每三分钟运行一次,但只在下午和晚上11点
    job = newJob(SimpleQuartzJob.class).withIdentity("job4", "group1").build();
    trigger = newTrigger().withIdentity("trigger4", "group1").withSchedule(cronSchedule("0 0/3 17-23 * * ?")).build();
    ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: "
    + trigger.getCronExpression());
    // job 5 will run at 10am on the 1st and 15th days of the month 将运行在每月的第一天和第十五天的10点
    job = newJob(SimpleQuartzJob.class).withIdentity("job5", "group1").build();
    trigger = newTrigger().withIdentity("trigger5", "group1").withSchedule(cronSchedule("0 0 10am 1,15 * ?")).build();
    ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: "
    + trigger.getCronExpression());
    // job 6 will run every 30 seconds but only on Weekdays (Monday through Friday) 将运行每30秒,但只在平日(星期一至星期五)
    job = newJob(SimpleQuartzJob.class).withIdentity("job6", "group1").build();
    trigger = newTrigger().withIdentity("trigger6", "group1").withSchedule(cronSchedule("0,30 * * ? * MON-FRI"))
    .build();
    ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: "
    + trigger.getCronExpression());
    // job 7 will run every 30 seconds but only on Weekends (Saturday and Sunday) 将运行每30秒,但只在周末(星期六和星期日)
    job = newJob(SimpleQuartzJob.class).withIdentity("job7", "group1").build();
    trigger = newTrigger().withIdentity("trigger7", "group1").withSchedule(cronSchedule("0,30 * * ? * SAT,SUN"))
    .build();
    ft = sched.scheduleJob(job, trigger);
    log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: "
    + trigger.getCronExpression());
    sched.start();
    log.info("------- Waiting five minutes... ------------");
    try {
    // wait five minutes to show jobs
    Thread.sleep(300L * 1000L);
    // executing...
    } catch (Exception e) {
    //
    }
    log.info("------- Shutting Down ---------------------");
    sched.shutdown(true);
    log.info("------- 打印已完成的Job -----------------");
    SchedulerMetaData metaData = sched.getMetaData();
    log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");
    }
    public static void main(String[] args) throws Exception {
    CronTriggerTest example = new CronTriggerTest();
    example.run();
    }
    }

实现简单的触发器SimpleTrigger与CronTrigger区别

http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/tutorial-lesson-06.html

持久化数据库

文章目录
  1. 1. 相关文摘
  2. 2. 添加quartz依赖包
  3. 3. 实现简单的触发器SimpleTrigger
  4. 4. 实现定时触发器CronTrigger
  5. 5. 实现简单的触发器SimpleTrigger与CronTrigger区别
  6. 6. 持久化数据库
,