相关文章

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. Wireshark对常见视频应用的抓包分析的结果

    一.PC端直播: YY客户端直播用的udp(P2P)9158客户端直播用的rtp/rtcp 二.Web端直播: YY网页端直播用的tcp9158网页端直播用的tcp六间房网页端直播用的tcp17173 ...

  2. Recurrent Neural Network系列2--利用Python,Theano实现RNN

    作者:zhbzz2007 出处:http://www.cnblogs.com/zhbzz2007 欢迎转载,也请保留这段声明.谢谢! 本文翻译自 RECURRENT NEURAL NETWORKS T ...

  3. Bootstrap入门(三)<p>标签的css样式

    Bootstrap入门(三)<p>标签的css样式 前提:引入css文件,内容放在一个class为container的div中   <p>标签属性 1.“ text-left ...

  4. Jsoup后台解析html、jsp网页

    在一些网络爬虫或者从第三方网站抓取信息的程序都面临1个问题,如何从网页中把所需的信息提取出来,Jsoup是个比较好的选择,它能把网站内容解析成Document,再从document中取element就 ...

  5. 如何让Docker容器随宿主机的启动而自动启动

    使用Docker容器部署服务时,不仅需要让服务随Docker容器的启动而启动,还需要让Docker容器随宿主机的启动而自动启动,为此Docker提供了Docker run的restart参数 #doc ...

  6. POJ1088(dp)

    滑雪 Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 91574   Accepted: 34573 Description ...

  7. 用反射技术替换工厂种的switch分支(14)

    首先给大家拜个晚年,祝大家新春快乐,万事如意,鸡年大吉. 好了,前面我们讲了很多的工厂模式,其中,有个很明显的特点,工厂中,有一个方法,里面有很多的swich case  分支,我们前面说过,我们可以 ...

  8. PS切图篇(一)---界面设置

    #工作区设置 四大主要面板:信息 字符  图层 历史记录 打开必要属性: 选择工具设置 选择图层的方式:ctrl+鼠标左击想选择的图层

  9. 理解Node.js的事件轮询

    前言 总括 : 原文地址:理解Node.js的事件轮询 Node小应用:Node-sample 智者阅读群书,亦阅历人生 正文 Node.js的两个基本概念 Node.js的第一个基本概念就是I/O操 ...

  10. java字节数组格式化为十六进制字符串

    /** * 格式化byte * * @param b * @return */ public static String byte2hex(byte[] b) { char[] Digit = { ' ...