quartz 概述

quartz是由Java编写的一款调度程序,github的地址:https://github.com/quartz-scheduler/quartz

Quartz使用

Schedulers是由工厂方法生成的。
Scheduler Job会在调用start()之后才会开始执行。

使用Scheduling API

扩展接口Job,在里面的execute()方法里即可编写被调度程序的逻辑代码.

1
2
3
4
5
6
7
8
9
public class MyJob implements org.quartz.Job {

public MyJob() {
}

public void execute(JobExecutionContext context) throws JobExecutionException {
System.err.println("Hello World! MyJob is executing.");
}
}

然后将Job与触发Trigger加入到调度周期里就可以运行了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// define the job and tie it to our MyJob class
JobDetail job = newJob(MyJob.class)
.withIdentity("job1", "group1")
.build();

// Trigger the job to run now, and then repeat every 40 seconds
Trigger trigger = newTrigger()
.withIdentity("trigger1", "group1")
.startNow()
.withSchedule(simpleSchedule()
.withIntervalInSeconds(40)
.repeatForever())
.build();

// Tell quartz to schedule the job using our trigger
scheduler.scheduleJob(job, trigger);

quartz各个组件之间的关系图

参考链接