一、Quartz下载
Quartz官网:http://www.quartz-scheduler.org/
以2.2.3版本为例,下载 Quartz 2.2.3 .tar.gz,解压,把quartz-2.2.3-distribution\quartz-2.2.3\lib
目录下jar包添加到工程中即可,如果使用maven,添加一下依赖:
<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>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
二、入门例子
先写一个类,MyJob.Java,注意,这个类一定要是public的。
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.util.Date;
public class MyJob implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("My QuarTz Job");
System.out.println("执行时间:"+new Date());
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
再写一个QuartzTest.java,实现每天24:00执行MyJob中的任务:
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import java.util.Date;
public class QuartzTest{
public static void main(String[] args) {
//创建一个SchedulerFactory对象
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = null;
try {
//通过SchedulerFactory对象获取任务调度器
scheduler = schedulerFactory.getScheduler();
//创建一个job
JobDetail job = JobBuilder.newJob(MyJob.class)
.withIdentity("job1", "group1")
.build();
//定义触发器,也就是执行job的规则
Trigger trigger=TriggerBuilder.newTrigger()
.withSchedule(CronScheduleBuilder.cronSchedule("0 0 0 * * ?"))
.build();
//把job和触发器注册到调度器中
scheduler.scheduleJob(job,trigger);
//启动调度器
scheduler.start();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
- 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
- 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
执行QuartzTest类中的main方法,等到00:00的时候就会执行MyJob中的任务:
My Quartz Job
执行时间:Tue Aug 01 00:00:00 CST 2017