一、都有哪些定时器
JDK自带的Timer、ScheduledThreadPoolExecutor
Spring提供的Scheduled
Quarts
xxl-job:分布式
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/62c61be77b2ded9f25f5069c5858810c.png)
二、JDK提供的定时线程池
定时线程池;ScheduledThreadPoolExecutor schedule = new ScheduledThreadPoolExecutor(1);
public static void main(String[] args) {
ScheduledThreadPoolExecutor schedule = new ScheduledThreadPoolExecutor(1);
//延时Runnable任务(只执行一次)
schedule.schedule(new Runnable() {
@Override
public void run() {
System.out.println("任务只执行一次");
}
}, 3, TimeUnit.SECONDS);
//固定延时间隔执行任务
schedule.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
System.out.println("固定延时间隔");
}
}, 1, 1, TimeUnit.SECONDS);
//固定时间间隔执行任务
schedule.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("固定时间间隔");
}
}, 1, 1, TimeUnit.SECONDS);
}
三、Spring提供的定时任务
一、概述
Cron表达式是一个字符串,字符串以5或6个空格隔开,中间均由空格隔开,分为6或7个域,每一个域代表一个含义,Cron有如下两种语法格式:
1.Seconds Minutes Hours DayofMonth Month DayofWeek Year 秒 分 小时 几号 几月 周几 年
2.Seconds Minutes Hours DayofMonth Month DayofWeek 秒 分 小时 几号 几月 周几
二、符号详细说明
* 表示匹配该域的任意值,假如在Minutes域使用*, 即表示每分钟都会触发事件
*/n 表示每隔n久执行一次
? 只能用在DayofMonth和DayofWeek两个域。它也匹配域的任意值,但实际不会。因为DayofMonth和 DayofWeek会相互影响。例如想在每月的20日
触发调度,不管20日到底是星期几,则只能使用如下写法: 13 13 15 20 * ?, 其中最后一位只能用?,而不能使用*,如果使用*表示不管星期
几都会触发,实际上并不是这样。
- 表示范围,例如在Minutes域使用5-20,表示从5分到20分钟每分钟触发一次
, 表示列出枚举值值。例如:在Minutes域使用5,20,则意味着在5和20分每分钟触发一次
L 表示最后,只能出现在DayofWeek和DayofMonth域,如果在DayofWeek域使用5L,意味着在最后的一个星期四触发。
W 表示有效工作日(周一到周五),只能出现在DayofMonth域,系统将在离指定日期的最近的有效工作日触发事件。例如:在 DayofMonth使用5W,如果5日是星期六,则将在最近的工作日:星期五,即4日触发。如果5日是星期天,则在6日(周一)触发;如果5日在星期一 到星期五中的一天,则就在5日触发。另外一点,W的最近寻找不会跨过月份。
LW 这两个字符可以连用,表示在某个月最后一个工作日,即最后一个星期五。
# 用于确定每个月第几个星期几,只能出现在DayofMonth域。例如在4#2,表示某月的第二个星期三。
三、举几个例子:
如果不知道怎么写,可以打开http://localhost:8080/xxl-job-admin/jobinfo新建任务
每三个月执行一次:"0 0 0 1 */3 ?"
每隔5秒执行一次:"*/5 * * * * ?"
每隔1分钟执行一次:"0 */1 * * * ?"
每天23点执行一次:"0 0 23 * * ?"
每天凌晨1点执行一次:"0 0 1 * * ?"
每月1号凌晨1点执行一次:"0 0 1 1 * ?"
每月最后一天23点执行一次:"0 0 23 L * ?"
每周星期天凌晨1点实行一次:"0 0 1 ? * L"
在26分、29分、33分执行一次:"0 26,29,33 * * * ?"
每天的0点、13点、18点、21点都执行一次:"0 0 0,13,18,21 * * ?"
表示在每月的1日的凌晨2点调度任务:"0 0 2 1 * ? *"
表示周一到周五每天上午10:15执行作业:"0 15 10 ? * MON-FRI"
表示2002-2006年的每个月的最后一个星期五上午10:15执行:"0 15 10 ? 6L 2002-2006"
四、案例
SpringBoot启动类要加上注解@EnableScheduling或者定时类上加注解@EnableScheduling
@Component
@EnableScheduling
public class PromotionSchedule {
@Scheduled(cron = "0 0 0 * * ?")
@Transactional(rollbackFor = Exception.class)
public void movePriceExecOrgList() {
System.out.println("进入定时器");
}
}
@Component
@EnableScheduling
public class PromotionSchedule {
private final PromotionService promotionService;
private final PromotionPushUserRepository promotionPushUserRepository;
public PromotionSchedule(PromotionService promotionService, PromotionPushUserRepository promotionPushUserRepository) {
this.promotionService = promotionService;
this.promotionPushUserRepository = promotionPushUserRepository;
}
@Scheduled(cron = "0 0 0 * * ?")
@Transactional(rollbackFor = Exception.class)
public void movePriceExecOrgList() {
System.out.println("进入推送定时器");
List<String> promotionSettingIdList = promotionPushUserRepository.promotionPushUserScheduleList();
if (!CollectionUtils.isEmpty(promotionSettingIdList)) {
for (String promotionSettingId : promotionSettingIdList) {
promotionService.promotionPush(promotionSettingId, "system");
}
}
}
}
四、xxl-job分布式任务调度平台
xxl官网
xxl分布式任务调度平台文档
源码仓库(码云)
1、为什么需要分布式任务调度器:
假设一个库存微服务集群部署了三个节点,如果采用JDK或者Spring的定时器,
那么就会在三台服务器各执行一次,总共执行了三次,但我们只要执行一次
2、源码目录说明
xxl-job-admin:调度中心,理解为服务端(作用:统一管理任务调度平台上调度任务,负责触发调度执行,并且提供任务管理平台。)
xxl-job-core:公共依赖
xxl-job-executor-samples:执行器Sample示例(选择合适的版本执行器,可直接使用,也可以参考其并将现有项目改造成执行器)
:xxl-job-executor-sample-springboot:Springboot版本,通过Springboot管理执行器,推荐这种方式;
:xxl-job-executor-sample-frameless:无框架版本;
3、配置部署"调度中心",理解为服务端
1、创建数据库,执行项目下/doc/db/tables_xxl_job.sql
2、更改admin配置文件数据库信息和邮件信息
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/xxl_job?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root_pwd
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.mail.host=smtp.qq.com
spring.mail.port=25
spring.mail.username=xxx@qq.com
spring.mail.password=xxx
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
xxl.job.accessToken=
xxl.job.i18n=zh_CN
xxl.job.triggerpool.fast.max=200
xxl.job.triggerpool.slow.max=100
xxl.job.logretentiondays=30
3、启动admin文件下的Application服务就可访问调度中心页面
路径:http://localhost:8080/xxl-job-admin
账号密码为:admin/123456
4、客户端配置(可在自己的业务项目中配置)
1、pom文件中引入了 "xxl-job-core" 的maven依赖
<dependency>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-job-core</artifactId>
</dependency>
2、配置文件
xxl.job.admin.addresses=http://127.0.0.1:8080/xxl-job-admin
xxl.job.accessToken=default_token
xxl.job.executor.appname=xxl-job-executor-sample
xxl.job.executor.address=
xxl.job.executor.ip=
xxl.job.executor.port=9999
xxl.job.executor.logpath=/data/applogs/xxl-job/jobhandler
xxl.job.executor.logretentiondays=30
3、XxlJobConfig.java
package com.xxl.job.executor.core.config;
import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class XxlJobConfig {
private Logger logger = LoggerFactory.getLogger(XxlJobConfig.class);
@Value("${xxl.job.admin.addresses}")
private String adminAddresses;
@Value("${xxl.job.accessToken}")
private String accessToken;
@Value("${xxl.job.executor.appname}")
private String appname;
@Value("${xxl.job.executor.address}")
private String address;
@Value("${xxl.job.executor.ip}")
private String ip;
@Value("${xxl.job.executor.port}")
private int port;
@Value("${xxl.job.executor.logpath}")
private String logPath;
@Value("${xxl.job.executor.logretentiondays}")
private int logRetentionDays;
@Bean
public XxlJobSpringExecutor xxlJobExecutor() {
logger.info(">>>>>>>>>>> xxl-job config init.");
XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
xxlJobSpringExecutor.setAppname(appname);
xxlJobSpringExecutor.setAddress(address);
xxlJobSpringExecutor.setIp(ip);
xxlJobSpringExecutor.setPort(port);
xxlJobSpringExecutor.setAccessToken(accessToken);
xxlJobSpringExecutor.setLogPath(logPath);
xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays);
return xxlJobSpringExecutor;
}
}
5、客户端使用
1、在业务系统中新建XxlJob类(类可以有多个方法,每个方法为一个定时器)
package com.autel.cloud.app.ocpi.job;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
@Slf4j
@RefreshScope
@Component
public class PullDataJob {
@XxlJob(value = "Job2Handler")
public ReturnT<String> pullData(@RequestBody String param) {
log.info("开始拉取数据任务执行了");
XxlJobLogger.log("开始拉取数据任务执行了");
return ReturnT.SUCCESS;
}
@XxlJob(value = "Job3Handler")
public ReturnT<String> job3(@RequestBody String param) {
log.info("Job3Handler执行了");
XxlJobLogger.log("Job3Handler");
return ReturnT.SUCCESS;
}
}
2、登录admin页面,在任务管理创建JobHandler名称的任务,填写内容见下面截图(使用默认JobHandler可以省略这一步骤)
路径:http://localhost:8080/xxl-job-admin
账号密码为:admin/123456
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7e8dd23e6b0afc90310965c86adc7e8a.png)