Quartz定时任务
一、Quartz中的概念
主要有三个核心概念:调度器、任务和触发器。三者关系简单来说就是,调度器负责调度各个任务,到了某个时刻或者过了一定时间,触发器触动了,特定任务便启动执行。概念相对应的类和接口有:
1 ) JobDetail :望文生义就是描述任务的相关情况:
2 ) Tigger :描述出发Jcb执行的时间触发规则。有SimpleTrigger和CronTigger两个子类代表两种方式,一种是每隔多少分钟小时执行,则用SimpieTrgger ;另-种是日历相关的重复时间间隔,如每天凌晨,每周星期一运行的话,通过Cron表达式便可定义出复杂的调度方案。
3) Scheculer :代表一个Quartz的独立运行容器 , TnggeriJobDetai要注册到Scheduler中才会生效,也就是让调度器知道有哪些触发器和任务,才能进行按规则进行调度任务。
二、使用,在maven仓库中下载jar包或者依赖,以下使用注解方式实现
三、spring的applicationContext2.xml配置文件
<?xml version="1.0" encoding="UTF-8"?> <!-- 加入头文件--> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task /spring-task.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd" > <!-- 扫描 --> <context:component-scan base-package="com.gx.job"></context:component-scan> <!-- 开启定义任务的注解使用 --> <task:annotation-driven/> </beans>
四、方法
/** * 任务 * @author Administrator * */ @Component public class MyJob1 { @Scheduled(cron =" 0/5 * * * * ? ")//每隔5秒执行一次 public void doTask() { System.out.println("定时任务的第一种实现方式"); } }
五、cron表达式可以在https://cron.qqe2.com/中自动生成
每10秒执行一次: 0/10 * * * * ?
每1分钟执行一次:0 0/1 * * * ? *
每1小时执行一次:0 0 0/1 * * ? *
每天晚上12点执行一次:0 0 0 * * ? *
每天晚上12点30分30执行一次:30 30 0 * * ? *
每月1号晚上12点30分30执行一次:30 30 0 1 * ? *
每年的1月1日12点执行一次:0 0 0 1 1 ? *

浙公网安备 33010602011771号