1, 简介
Quartz是一个任务调度框架。
核心类:
Scheduler :调度器,所有Job的调度都是由它控制;
JobDetail :生成Job对象的实例,存储Job对象需要的参数;
Job :执行业务逻辑;
Trigger :定义触发的条件;
帮助类
SimpleScheduleBuilder:用于构建Scheduler:
JobBuilder :用于构建JobDetail:
TriggerBuilder :用于构建Trigger;
2, 创建任务
public class Test
{
public static void schedue() throws SchedulerException
{
// 调度器
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
// 任务
JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity("job1", "group1").usingJobData("key", "value")
.build();
// 触发器
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1").startNow()
.withSchedule(simpleSchedule().withIntervalInSeconds(40).repeatForever()).build();
// 调度器关联任务JobDetail与触发器Trigger
scheduler.scheduleJob(job, trigger);
// 定时任务启动
scheduler.start();
}
public class MyJob implements org.quartz.Job
{
/*
* 具体的业务逻辑
*/
@Override
public void execute(JobExecutionContext context) throws JobExecutionException
{
JobDetail jobDetail = context.getJobDetail();
// 获取参数
JobDataMap jobDataMap = jobDetail.getJobDataMap();
jobDataMap.get("key");
}
}
public static void main(String[] args) throws SchedulerException
{
schedue();
}
}
备注:
Jobkey :JobDetail#getKey(),格式:group.name
TriggerKey : Trigger#getKey(), 格式:group.name
3, Cron表达式
例如:0 0 12 * * ?
4,其它
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>
官网地址: http://www.quartz-scheduler.org/