相关文章

Spring Boot 相关文章目录

前言

最近在项目中使用到定时任务,之前一直都是使用Quartz 来实现,最近看Spring 基础发现其实Spring 提供 Spring Schedule 可以帮助我们实现简单的定时任务功能。

下面说一下两种方式在Spring Boot 项目中的使用。

Spring Schedule 实现定时任务

Spring Schedule 实现定时任务有两种方式 1. 使用XML配置定时任务, 2. 使用 @Scheduled 注解。 因为是Spring Boot 项目 可能尽量避免使用XML配置的形式,主要说注解的形式.

Spring Schedule 提供三种形式的定时任务:

固定等待时间 @Scheduled(fixedDelay = 时间间隔 )

@Component
public class ScheduleJobs {
public final static long SECOND = 1 * 1000;
FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss"); @Scheduled(fixedDelay = SECOND * 2)
public void fixedDelayJob() throws InterruptedException {
TimeUnit.SECONDS.sleep(2);
System.out.println("[FixedDelayJob Execute]"+fdf.format(new Date()));
}
}

固定间隔时间 @Scheduled(fixedRate = 时间间隔 )

@Component
public class ScheduleJobs {
public final static long SECOND = 1 * 1000;
FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss"); @Scheduled(fixedRate = SECOND * 4)
public void fixedRateJob() {
System.out.println("[FixedRateJob Execute]"+fdf.format(new Date()));
}
}

Corn表达式 @Scheduled(cron = Corn表达式)

@Component
public class ScheduleJobs {
public final static long SECOND = 1 * 1000;
FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss"); @Scheduled(cron = "0/4 * * * * ?")
public void cronJob() {
System.out.println("[CronJob Execute]"+fdf.format(new Date()));
}
}

Spring Boot 整合 Quartz 实现定时任务

添加Maven依赖

        <dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>

Spring Boot 整合 Quartz

Spring 项目整合 Quartz 主要依靠添加 SchedulerFactoryBean 这个 FactoryBean ,所以在maven 依赖中添加 spring-context-support 。

首先添加 QuartzConfig 类 来声明相关Bean

@Configuration
public class QuartzConfig {
@Autowired
private SpringJobFactory springJobFactory; @Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean.setJobFactory(springJobFactory);
return schedulerFactoryBean;
} @Bean
public Scheduler scheduler() {
return schedulerFactoryBean().getScheduler();
}
}

这里我们需要注意 我注入了一个 自定义的JobFactory ,然后 把其设置为SchedulerFactoryBean 的 JobFactory。其目的是因为我在具体的Job 中 需要Spring 注入一些Service。

所以我们要自定义一个jobfactory, 让其在具体job 类实例化时 使用Spring 的API 来进行依赖注入。

SpringJobFactory 具体实现:

@Component
public class SpringJobFactory extends AdaptableJobFactory { @Autowired
private AutowireCapableBeanFactory capableBeanFactory; @Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
Object jobInstance = super.createJobInstance(bundle);
capableBeanFactory.autowireBean(jobInstance);
return jobInstance;
}
}

具体使用 (摘取自项目代码):


@Service
public class QuartzEventServiceImpl implements QuartzEventService {
private static final String JOB_GROUP = "event_job_group";
private static final String TRIGGER_GROUP = "event_trigger_group";
@Autowired
private Scheduler scheduler; @Override
public void addQuartz(Event event) throws SchedulerException {
JSONObject eventData = JSONObject.parseObject(event.getEventData());
Date triggerDate = eventData.getDate("date");
JobDetail job = JobBuilder.newJob(EventJob.class).withIdentity(event.getId().toString(), JOB_GROUP).usingJobData(buildJobDateMap(event)).build();
Trigger trigger = TriggerBuilder.newTrigger().withIdentity(event.getId().toString(), TRIGGER_GROUP).startAt(triggerDate).build();
scheduler.scheduleJob(job, trigger);
}

SpringBoot之旅 -- 定时任务两种(Spring Schedule 与 Quartz 整合 )实现的更多相关文章

  1. Springboot中IDE支持两种打包方式,即jar包和war包

    Springboot中IDE支持两种打包方式,即jar包和war包 打包之前修改pom.xml中的packaging节点,改为jar或者war    在项目的根目录执行maven 命令clean pa ...

  2. springboot之jackson的两种配置方式

    springboot 针对jackson是自动化配置的,如果需要修改,有两种方式: 方式一:通过application.yml 配置属性说明:## spring.jackson.date-format ...

  3. SpringBoot热部署的两种方式

    SpringBoot热部署方式一共有两种,分别使用两种不同的依赖 SpringBoot 1.3后才拥有SpringBoot devtools热部署 ①:spring-boot-devtools   ② ...

  4. SpringBoot自定义过滤器的两种方式及过滤器执行顺序

    第一种 @WebFilter + @ServletComponentScan 注解 1.首先自定义过滤器 如下自定义过滤器 ReqResFilter 必须实现  javax.servlet.Filte ...

  5. springboot集成websocket的两种实现方式

    WebSocket跟常规的http协议的区别和优缺点这里大概描述一下 一.websocket与http http协议是用在应用层的协议,他是基于tcp协议的,http协议建立链接也必须要有三次握手才能 ...

  6. springboot 热部署的两种方式

    问题的提出: 在编写代码的时候,你会发现我们只是简单把打印信息改变了,就需要重新部署,如果是这样的编码方式,那么我们估计一天下来就真的是打几个Hello World就下班了.那么如何解决热部署的问题呢 ...

  7. springboot工程pom的两种配置方式

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...

  8. 使用IDEA将springboot框架导入的两种方法

    第一种新建Maven,导入springboot所依赖的jar包   1.新建一个maven项目,下一步命名,保存文件地址,点击完成         2.进去springboot下载(点击进入),复制p ...

  9. 关于给springboot添加定时器的两种方式

    原文:https://blog.csdn.net/liboyang71/article/details/72781526 首先,搭建好一个springboot项目,可使用maven或者gradle或者 ...

随机推荐

  1. Handler消息传递机制——Handler类简洁

    Handler类的主要作用有两个: 在新启动的线程中发送消息. 在主线程中获取.处理消息. 上面的说法很简单,只要分成两步即可:在新启动的线程中发送消息:然后在主线程上获取.并处理消息.但这个过程涉及 ...

  2. Cocoa 新的依赖管理工具:Carthage

    昨天搞了一下pod的安装 因为之前我都是在使用pod来进行第三方库的管理 但是拿到项目之后 竟发现这个前辈是用Carthage 说真的在这之前我从来没有用过这个玩意因为我感觉用POD已经很好了啊 很方 ...

  3. 我用Cocos2d-x模拟《Love Live!学院偶像祭》的Live场景(一)

    同样从CSDN搬过来 博客开这么久了,就发过一篇很水的文章,一直想写点正式的东西.这次准备开工一个仿其他游戏的简单小游戏,于是开博客把开发过程记录下来.这一系列文章主要讲,我是如何从零开始使用Coco ...

  4. 配置FMS发布/HDS/HLS流

    一.前言 安装完FMS4.5以后就有了apache2.2,由于在FMS安装目录里面,他是对外面已经安装的是没有影响的,默认情况向, FMS监听80端口接收traffic然后传递给Apache的8134 ...

  5. Paxos 实现日志复制同步

    Paxos 实现日志复制同步 本篇文章以 John Ousterhout(斯坦福大学教授) 和 Diego Ongaro(斯坦福大学获得博士学位,Raft算法发明人) 在 Youtube 上的讲解视频 ...

  6. (四)Hololens Unity 开发之 凝视系统

    学习源于官方文档 Gaze in Unity 笔记一部分是直接翻译官方文档,部分各人理解不一致的和一些比较浅显的保留英文原文 HoloLens 有三大输入系统,凝视点.手势和声音 ~ 本文主要记录凝视 ...

  7. IOS获取经度纬度

    仔细研究了一下SDK文档,再结合网上的方法,写了这一个简单的获取经纬度的方法,大家看看就好. 首先要导入CoreLocation.Frame 包 .h 文件 1 2 3 4 5 6 7 8 9 #im ...

  8. java_JDBC字段对应

    地址: http://otndnld.oracle.co.jp/document/products/oracle10g/102/doc_cd/java.102/B19275-03/datacc.htm ...

  9. 福利:Axure 8.0 Pro 破解版下载

    今天从网上找了好久Axure 8.0 Pro版本 但是都不能用了,于是自己想到了这个办法 1.从官网下单 Axure 8.0 版本 官网地址:https://www.axure.com.cn/3510 ...

  10. PAT乙级 1065. 单身狗(25) by Python

    1065. 单身狗(25) 时间限制 300 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 CHEN, Yue "单身狗"是中文对 ...