本文的核心内容:Java中定时任务实现三种方式,quartz框架入门,quartz框架与Spring集成,quartz框架的集群。
什么是定时任务:
定时任务是指调度程序在指定的时间或周期触发执行的任务
使用场景:发送邮件、统计、状态修改、消息推送、活动开启
一、定时任务实现技术:
1. Java 自带的 java.util.Timer类,这个类允许你调度一个 java.util.TimerTask 任务。使用这种方式可以让你的程序按照某一个频度执行,但不能在指定时间运行。使用较少。
2. Spring3.0 以后自主开发的定时任务工具 spring task ,使用简单,支持线程池,可以高效处理许多不同的定时任务,除 spring 相关的包外不需要额外的包,支持注解和配置文件两种形式。 不能处理过于复杂的任务。
3. 专业的定时框架 quartz ,功能强大,可以让你的程序在指定时间执行,也可以按照某一个频度执行,支持数据库、监听器、插件、集群。
二:quartz框架入门【环境搭建】
引入Maven依赖
org.quartz-scheduler
quartz
2.2.1
org.quartz-scheduler
quartz-jobs
2.2.1
设置定时任务【实现Job接口的 execute方法。】
public class MyJob implements Job {
/* @Description:设置执行的任务
* @Param:
* @Return:
* @Author: Maps
* @Date: 2018/7/22 13:35
*/
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("time is :|"+new Date());
}
}
构建调度任务 :创建任务调度器 创建任务 创建触发器 组装调度任务 执行调度任务【start方法】
public class QuartzFirst {
public static void main(String[] args) throws Exception {
//获取任务调度器
Scheduler scheduler= StdSchedulerFactory.getDefaultScheduler();
//创建任务
JobDetail myJob= JobBuilder.newJob(MyJob.class)
.withIdentity("myJob","group1")
.build();
//触发器 指定触发器的认证信息,指定虚拟开启后运行
//每五秒触发一次
Trigger trigger= TriggerBuilder.newTrigger()
.withIdentity("myTrigger","group1")
.startNow()
.withSchedule(simpleSchedule().withIntervalInSeconds(5)
.repeatForever())
.build();
//组装任务对象
scheduler.scheduleJob(myJob,trigger);
//执行任务
scheduler.start();
}
}
三:quartz体系框架
Quartz的核心主要包括三部分:任务(Job)、触发器(Trigger)和调度器(Scheduler)
Job
Job是一个接口,只定义一个方法execute(JobExecutionContext context),在实现接口的execute方法中编写所需要定时执行的Job(任务), JobExecutionContext类提供了了调度应用的一些信息。Job运行时的信息保存在JobDataMap实例中。
JobDetail
JobDetail 定义的是任务数据,而真正的执行逻辑是在Job中。sheduler每次执行,都会根据JobDetail创建一个新的Job实例。
Trigger
Trigger是⼀个类,描述触发Job执行的时间触发规则。主要有SimpleTrigger和CronTrigger这两个子类。
当且仅当需调度一次或者以固定时间间隔周期执行调度,SimpleTrigger是最适合的选择;而CronTrigger则可以通过Cron表达式定义出各种复杂时间规则的调度⽅方案:如工作日周一到周五的15:00~16:00执行调度等
Cron表达式的格式:秒 分 时 日 月 周 年(可选)。
字段名 |
允许的值 |
允许的特殊字符 |
秒 |
0-59 |
, – * / |
分 |
0-59 |
, – * / |
时 |
0-23 |
, – * / |
日 |
1-31 |
, – * ? / L W C |
月 |
1-12 or JAN-DEC |
, – * / |
周 |
1-7 or SUN-SAT |
, – * ? / L C # MON FRI |
年(可选字段) |
empty, 1970-2099 |
, – * / |
Scheduler
Scheduler代表一个Quartz的独立运行容器, Trigger和JobDetail可以注册到Scheduler中, 两者在Scheduler中拥有各自的组及名称, 组及名称是Scheduler查找定位容器中某一对象的依据,Trigger的组及名称必须唯⼀, JobDetail的组和名称也必须唯一(但可以和Trigger的组和名称相同,因为它们是不同类型的)。Scheduler定义了多个接口方法, 允许外部通过组及名称访问和控制容器中Trigger和JobDetail。
四:quartz框架与Spring集成
导入quartz与Spring框架的Maven依赖【代码省略】
Spring的配置文件
启动Spring工厂测试
public static void main(String[] args) throws Exception {
ApplicationContext ctx=new ClassPathXmlApplicationContext("classpath:/application-context.xml");
}
五:定时任务的存储方式【RAMJobStore和JDBCJobStore】
类型 | 优点 | 缺点 |
---|---|---|
RAMJobStore(默认) | 不要外部数据库,配置容易,运行速度快 | 因为调度程序信息是存储在被分配给JVM的内存里面,所以,当应用程序停止运行时,所有调度信息将被丢失。另外因为存储到JVM内存里面,所以可以存储多少个Job和Trigger将会受到限制 |
JDBCJobStore | 支持集群,因为所有的任务信息都会保存到数据库中,可以控制事物,还有就是如果应用服务器关闭或者重启,任务信息都不会丢失,并且可以恢复因服务器关闭或者重启而导致执行失败的任务 | 运行速度的快慢取决与连接数据库的快慢 |
设置 JDBCJobStore
在应用程序中设置使用 JDBCJobStore
需要两步:首先必须创建作业仓库使用的数据库表。JDBCJobStore
与所有主流数据库都兼容,而且 Quartz 提供了一系列创建表的 SQL 脚本,能够简化设置过程。可以在 Quartz 发行包的 “docs/dbTables”目录中找到创建表的 SQL 脚本。第二,必须定义一些属性
创建Quartz数据库表
在 quartz.properties文件中指定JDBCJobStore
属性
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 10
org.quartz.threadPool.threadPriority = 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true
# Using RAMJobStore
## if using RAMJobStore, please be sure that you comment out the following
## - org.quartz.jobStore.tablePrefix,
## - org.quartz.jobStore.driverDelegateClass,
## - org.quartz.jobStore.dataSource
#org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
# Using JobStoreTX
## Be sure to run the appropriate script(under docs/dbTables) first to create tables
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
# Configuring JDBCJobStore with the Table Prefix
org.quartz.jobStore.tablePrefix = QRTZ_
# Using DriverDelegate
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
# Using datasource
org.quartz.jobStore.dataSource = qzDS
# Define the datasource to use
org.quartz.dataSource.qzDS.driver = com.mysql.jdbc.Driver
org.quartz.dataSource.qzDS.URL = jdbc:mysql://localhost:3306/quartz
org.quartz.dataSource.qzDS.user = root
org.quartz.dataSource.qzDS.password = root
org.quartz.dataSource.qzDS.maxConnections = 30
修改Spring的配置文件【加载配置文件】
六:quarzt的集群支持
虽然单个Quartz实例能给予你很好的Job调度能力,但它不能满足典型的企业需求,如可伸缩性、高可靠性满足。假如你需要故障转移的能力并能运行日益增多的 Job,Quartz集群势必成为你应用的一部分了。使用 Quartz 的集群能力可以更好的支持你的业务需求,并且即使是其中一台机器在最糟的时间崩溃了也能确保所有的 Job 得到执行。
一个 Quartz 集群中的每个节点是一个独立的 Quartz 应用,它又管理着其他的节点。意思是你必须对每个节点分别启动或停止。不像许多应用服务器的集群,独立的 Quartz 节点并不与另一其的节点或是管理节点通信。Quartz 应用是通过数据库表来感知到另一应用的。
准备配置文件
org.quartz.scheduler.instanceName: TestScheduler
org.quartz.scheduler.instanceId: auto
org.quartz.scheduler.skipUpdateCheck: true
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 10
org.quartz.threadPool.threadPriority = 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true
# Using RAMJobStore
## if using RAMJobStore, please be sure that you comment out the following
## - org.quartz.jobStore.tablePrefix,
## - org.quartz.jobStore.driverDelegateClass,
## - org.quartz.jobStore.dataSource
#org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
# Using JobStoreTX
## Be sure to run the appropriate script(under docs/dbTables) first to create tables
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.isClustered = true
# Configuring JDBCJobStore with the Table Prefix
org.quartz.jobStore.tablePrefix = QRTZ_
# Using DriverDelegate
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
# Using datasource
org.quartz.jobStore.dataSource = qzDS
# Define the datasource to use
org.quartz.dataSource.qzDS.driver = com.mysql.jdbc.Driver
org.quartz.dataSource.qzDS.URL = jdbc:mysql://localhost:3306/quartz
org.quartz.dataSource.qzDS.user = root
org.quartz.dataSource.qzDS.password = root
org.quartz.dataSource.qzDS.maxConnections = 30
启动spring工厂并测试