相关文章

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. 纯代码实现CSS圆角

    我这里说的是纯代码,是指的不使用图片实现圆角,图片实现圆角,这里就不说了. 纯代码实现圆角主要有3种方法: 第一种:CSS3圆角   #chaomao{     border-radius:2px 2 ...

  2. 记一次DG搭建过程中ORA-09925: Unable to createaudit trail file 错误

    今天做Oracle DG  编写initorcl的时候,修改完以后,sqlplus就不能再登陆,一直报 ERROR: ORA-09925: Unable to createaudit trail fi ...

  3. jQuery 动画的执行

    jQuery 动画的执行 <%@ page language="java" import="java.util.*" pageEncoding=" ...

  4. easyUI linkbutton组件

    easyUI linkbutton组件: <!DOCTYPE html> <html lang="en"> <head> <meta ch ...

  5. HDU1394(线段树||树状数组)

    Minimum Inversion Number Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java ...

  6. git命令实战之血泪记录

    注意: 本文章所写所有命令均在Git命令行窗口执行!非cmd窗口! 打开git命令行窗口步骤为:到项目根目录下执行bash命令行操作:右键点击Git Bash Here菜单,打开git命令窗口,不是c ...

  7. Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be

    有些操作只能回到主线程操作 比如: mbprogresshud只能在主线程中使用 而且注意凡是关于布局的代码也只能下载主线程

  8. Exception in thread "main" org.hibernate.HibernateException: save is not valid without active transaction

    在spring4+hibernate4整合过程中,使用@Transactional注解事务会报"Exception in thread "main" org.hibern ...

  9. 使用nat方式解决虚拟机联网问题

    本文全文参考:http://jingyan.baidu.com/album/4e5b3e1957979d91901e24f1.html?picindex=1,谢谢 对于很多的linux初学者来说,最开 ...

  10. Wpf中鼠标样式的修改,作用点修改

    最近,在做一个控件的鼠标样式,Ps加了插件,可以编辑生成.cur格式的图标. 可是,所有的改完以后,调试运行,结果发现自己制作的图标的作用点总是在左上角,而不是在"手形"图标的食指 ...