相关文章

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. Carthage - 一个简单、去集中化的Cocoa依赖管理器

    作为一名新时代的90后猿 在swift大势所趋的时候  怎能不会Carthage 配置它其实很简单  下面我们一步一步来 (1)打开你的终端 输入 brew update brew install c ...

  2. HDFS存储系统

    HDFS存储系统 一.基本概念 1.NameNode HDFS采用Master/Slave架构.namenode就是HDFS的Master架构.主要负责HDFS文件系统的管理工作,具体包括:名称空间( ...

  3. App Store Review Guideline(带翻译)

    1. Terms and conditions(法律与条款) 1.1  As a developer of applications for the App Store you are bound b ...

  4. Bootstrap Paginator分页插件+ajax 实现动态无刷新分页

    之前做分页想过做淘宝的那个,但是因为是后台要求不高,就Bootstrap Paginator插件感觉还蛮容易上手,所以就选了它. Bootstrap Paginator分页插件下载地址: Downlo ...

  5. HDU 2568[前进]模拟

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2568 关键思想:傻傻地模拟 代码如下: #include<iostream> using ...

  6. RAS 加密 解密

    蚂蚁金服电话面试时,问到了RAS加密解密,感觉回答的有点模糊,遂写个例子加深一下印象 package cheng.test.cipher;import java.io.FileInputStream; ...

  7. 自己动手系列——实现一个简单的ArrayList

    ArrayList是Java集合框架中一个经典的实现类.他比起常用的数组而言,明显的优点在于,可以随意的添加和删除元素而不需考虑数组的大小.处于练手的目的,实现一个简单的ArrayList,并且把实现 ...

  8. GTK+基本图元的绘制

    // main.c #include <gtk/gtk.h> static void draw_round_rectangle (cairo_t * cr, double x, doubl ...

  9. 分享jquery.cookie.js

    代码如下: /*! * jQuery Cookie Plugin v1.4.1 * https://github.com/carhartl/jquery-cookie * * Copyright 20 ...

  10. 创建Win32图形界面应用程序

    没有什么比创建一个Win32图形界面应用程序能让Win32汇编初学者更兴奋的了! 然而,对于像我这样没有代码便会陷入困境的人来说,看到下面的代码总能让人为之一振,百余行的代码使得Win32GUI编程并 ...