Quartz简介及应用场景
Quartz介绍
Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,完全由Java开发,可以用来执行定时任务,类似于java.util.Timer。但是相较于Timer, Quartz增加了很多功能:
持久性作业 - 就是保持调度定时的状态;
作业管理 - 对调度作业进行有效的管理;
图解quartz工作流程
Quartz相关表达式 在线生成自定义表达式
创建新的项目
导入相关pom依赖
<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>
Demo1
package com.chen.quartz01.demo;
import com.chen.quartz01.job.RamJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import static org.quartz.JobBuilder.newJob;
/**
* @author嘟嘟
*/
public class Demo1 {
public static void main(String[] args) throws SchedulerException {
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler scheduler = sf.getScheduler();
JobDetail jobDetail = newJob(RamJob.class)
.withIdentity("job1","group1")
.withDescription("this is a job")
.build();
Trigger trigger =(Trigger) TriggerBuilder.newTrigger()
//每隔6秒执行一次,共计3次
// .withSchedule(SimpleScheduleBuilder.repeatSecondlyForTotalCount(3,6))
//每天23:34执行一次
// .withSchedule(CronScheduleBuilder.cronSchedule("0 34 23 * * ?"))
///6秒更新一次
.withSchedule(CronScheduleBuilder.cronSchedule("0/6 * * * * ?"))
.withDescription("this is a trigger")
.build();
scheduler.scheduleJob(jobDetail,trigger);
scheduler.start();
}
}
运行测试
Quartz中参数传递
有两种传参方式
第一种就是直接定义
通过JobDataMap在我的调度器这边存储参数,并可以在Job中取出来,实现传参
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler scheduler = sf.getScheduler();
JobDetail jobDetail = newJob(RamJob.class)
.withIdentity("job1","group1")
.withDescription("this is a job")
.usingJobData("name","zhangsan")
.build();
JobDataMap jobDataMap = jobDetail.getJobDataMap();
jobDataMap.put("job","司机");
jobDataMap.put("level","老师");
关于Spring task && Quartz的优缺点
Spring task
优点:无需整合spring,作业类中就可以调用业务service
缺点:单线程;不能做数据存储型的定时任务
Quartz
优点:多线程;可以做数据存储型的定时任务,维护性高;
缺点:需要整合spring,不能直接调用业务层service;
package com.chen.quartz01.task;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
/**
* @author嘟嘟
*/
@Service
public class SpringTask {
@Scheduled(cron = "0/10 * * * * ?")
public void xx(){
// 10s执行下面打印那么意味着spring task是多线程的
// 30s执行下面打印,那么意味着单线程
System.out.println("每十秒执行一次的Sping task。。"+System.currentTimeMillis());
try {
Thread.sleep(20*1000);
System.out.println("处理大数据量的耗时操纵。。。");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}