springBoot定时任务可分为多线程和单线程,而单线程又分为注解形式,接口形式

1.基于注解形式

基于注解@Scheduled默认为单线程,开启多个任务时,任务的执行时机会受上一个任务执行时间的影响。

  1)创建定时器

  使用SpringBoot基于注解来创建定时任务非常简单,只需几行代码便可完成。 代码如下

  

package com.cst.klocwork.service.cron;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; import com.cst.util.string.LocalDateTimes; @Component
@Configuration //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class Test {
//3.添加定时任务
@Scheduled(cron = "0/5 * * * * ?")
//或直接指定时间间隔,例如:5秒
//@Scheduled(fixedRate=5000)
private void configureTasks() {
f1();
} public void f1() {
System.err.println("执行静态定时任务时间:=== " + LocalDateTimes.nowFormat());
}
}

  Cron表达式参数分别表示:

  • 秒(0~59) 例如0/5表示每5秒
  • 分(0~59)
  • 时(0~23)
  • 日(0~31)的某天,需计算
  • 月(0~11)
  • 周几( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)

  @Scheduled:除了支持灵活的参数表达式cron之外,还支持简单的延时操作,例如 fixedDelay ,fixedRate 填写相应的毫秒数即可。

  2)启动测试

  启动springBoot项目,可以看到控制台打印出如下信息:

  

  显然,使用@Scheduled 注解很方便,但缺点是当我们调整了执行周期的时候,需要重启应用才能生效,这多少有些不方便。为了达到实时生效的效果,可以使用接口来完成定时任务。

2.基于接口

  1)导入依赖包:

 <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.0.4.RELEASE</version>
</parent> <dependencies>
<dependency><!--添加Web依赖 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><!--添加MySql依赖 -->
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency><!--添加Mybatis依赖 配置mybatis的一些初始化的东西-->
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency><!-- 添加mybatis依赖 -->
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
<scope>compile</scope>
</dependency>
</dependencies>

    2)添加数据库记录:

DROP DATABASE IF EXISTS `socks`;
CREATE DATABASE `socks`;
USE `SOCKS`;
DROP TABLE IF EXISTS `cron`;
CREATE TABLE `cron` (
`cron_id` varchar(30) NOT NULL PRIMARY KEY,
`cron` varchar(30) NOT NULL
);
INSERT INTO `cron` VALUES ('1', '0/5 * * * * ?');

  然后在项目中的application.properties添加数据库的配置

3.创建定时器

  数据库准备好数据之后,我们编写定时任务,注意这里添加的是TriggerTask,目的是循环读取我们在数据库设置好的执行周期,以及执行相关定时任务的内容。
具体代码如下:

bean类:

package com.cst.klocwork.bean.cron;

import com.cst.util.bean.IBean;
import lombok.Data;
import lombok.experimental.Accessors; @Accessors(chain = true)
@Data
public class Cron implements IBean{
private static final long serialVersionUID = 1L;
private String cron_id;
private String cron; }

mapper类:

package com.cst.klocwork.bean.cron;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component; import com.baomidou.mybatisplus.core.mapper.BaseMapper; @Mapper
@Component
public interface CronMapper extends BaseMapper<Cron>{ @Select("select cron from cron where cron_id = '1'")
String getCron(); }

 定时器任务类:

package com.cst.klocwork.service.cron;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils; import com.cst.klocwork.bean.cron.CronMapper;
import com.cst.util.string.LocalDateTimes; @Component
@Configuration //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class DynamicScheduleTask implements SchedulingConfigurer { @Autowired //注入mapper
private CronMapper cronMapper; /**
* 执行定时任务.
*/
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.addTriggerTask(
//1.添加任务内容(Runnable)
() -> f1(),
//2.设置执行周期(Trigger)
triggerContext -> {
//2.1 从数据库获取执行周期
String cron = cronMapper.getCron();
//2.2 合法性校验.
if (StringUtils.isEmpty(cron)) {
// Omitted Code ..
}
//2.3 返回执行周期(Date)
return new CronTrigger(cron).nextExecutionTime(triggerContext);
}
);
} public void f1() {
System.err.println("执行动态定时任务: " + LocalDateTimes.nowFormat());
}
}

  4)、启动测试

  启动springBoot项目后,查看控制台,打印时间是我们预期的每10秒一次:

  如果此处想修改运行周期,只需要修改数据库里的时间即可改变运行周期。并且不需要我们重启应用,十分方便。

  注意: 如果在数据库修改时格式出现错误,则定时任务会停止,即使重新修改正确;此时只能重新启动项目才能恢复。

3.多线程定时任务

  基于注解设定多线程定时任务

  1)创建多线程定时任务

//@Component注解用于对那些比较中立的类进行注释;
//相对与在持久层、业务层和控制层分别采用 @Repository、@Service 和 @Controller 对分层中的类进行注释
@Component
@EnableScheduling // 1.开启定时任务
@EnableAsync // 2.开启多线程
public class MultithreadScheduleTask { @Async
@Scheduled(fixedDelay = 1000) //间隔1秒
public void first() throws InterruptedException {
System.out.println("第一个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
System.out.println();
Thread.sleep(1000 * 10);
} @Async
@Scheduled(fixedDelay = 2000)
public void second() {
System.out.println("第二个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
System.out.println();
}
}

  2)启动springBoot项目后

  查看控制台

  

从控制台可以看出,第一个定时任务和第二个定时任务互不影响;

并且,由于开启了多线程,第一个任务的执行时间也不受其本身执行时间的限制,所以需要注意可能会出现重复操作导致数据异常。

SpringBoot的定时任务的更多相关文章

  1. 玩转SpringBoot之定时任务详解

    序言 使用SpringBoot创建定时任务非常简单,目前主要有以下三种创建方式: 一.基于注解(@Scheduled) 二.基于接口(SchedulingConfigurer) 前者相信大家都很熟悉, ...

  2. SpringBoot 配置定时任务

    SpringBoot启用定时任务,其内部集成了成熟的框架,因此我们可以很简单的使用它. 开启定时任务 @SpringBootApplication //设置扫描的组件的包 @ComponentScan ...

  3. SpringBoot - 添加定时任务

    SpringBoot 添加定时任务 EXample1: import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spri ...

  4. springboot之定时任务

    定时线程 说到定时任务,通常会想到JDK自带的定时线程来执行,定时任务. 回顾一下定时线程池. public static ScheduledExecutorService newScheduledT ...

  5. SpringBoot整合定时任务和异步任务处理 3节课

    1.SpringBoot定时任务schedule讲解   定时任务应用场景: 简介:讲解什么是定时任务和常见定时任务区别 1.常见定时任务 Java自带的java.util.Timer类        ...

  6. 十三、springboot集成定时任务(Scheduling Tasks)

    定时任务(Scheduling Tasks) 在springboot创建定时任务比较简单,只需2步: 1.在程序的入口加上@EnableScheduling注解. 2.在定时方法上加@Schedule ...

  7. SpringBoot创建定时任务

    之前总结过spring+quartz实现定时任务的整合http://www.cnblogs.com/gdpuzxs/p/6663725.html,而springboot创建定时任务则是相当简单. (1 ...

  8. springboot开启定时任务 添加定时任务 推送

    最近在自学Java的springboot框架,要用到定时推送消息.参考了网上的教程,自己调试,终于调好了.下面将网上的教程归纳下,总结复习下.  springboot开启定时任务  在SpringBo ...

  9. (入门SpringBoot)SpringBoot结合定时任务task(十)

    SpringBoot整合定时任务task 使用注解EnableScheduling在启动类上. 定义@Component作为组件被容器扫描. 表达式生成地址:http://cron.qqe2.com ...

  10. SpringBoot整合定时任务和异步任务处理

    SpringBoot定时任务schedule讲解 简介:讲解什么是定时任务和常见定时任务区别 1.常见定时任务 Java自带的java.util.Timer类 timer:配置比较麻烦,时间延后问题, ...

随机推荐

  1. Part 23 to 26 Routing in Angular

    Part 23 AngularJS routing tutorial In general, as the application becomes complex you will have more ...

  2. 用Docker搭建RabbitMq的普通集群和镜像集群

    普通集群:多个节点组成的普通集群,消息随机发送到其中一个节点的队列上,其他节点仅保留元数据,各个节点仅有相同的元数据,即队列结构.消费者消费消息时,会从各个节点拉取消息,如果保存消息的节点故障,则无法 ...

  3. 【Linux】解压分卷压缩的zip文件

    例如linux.zip.001, linux.zip.002, linux.zip.003. 1. cat linux.zip* > linux.zip #合并为一个zip包. 2. unzip ...

  4. 双非本科进大疆(SP)!

    哈喽,大家好,我是仲一.今天和大家分享的是一位优秀双非本科生上岸大疆的经历(羡慕哭了...). 今年4月底的时候,这位学弟和我分享了他拿下oppo,京东,联发科实习offer的经历,当时我还发了朋友圈 ...

  5. 关于Cefsharp无法拖动Dom元素的解决方法

    如图所显示,Cefsharp在嵌入网页,页面有对Dom元素的拖动的操作,独立在浏览器上对网页元素的拖动是没有问题的,但是嵌入到Cefsharp上显示禁用的图标.排查了H5的代码,没有写入禁用拖动的操作 ...

  6. 微信小程序中途加入云开发之坑

    一开始未使用云开发的小程序项目,之后想使用云开发能力时,要先删除对应在开发者工具中的项目(先压缩备份源码!),再用开发者工具重新创建,很多时候都需要用这种方式进行处理

  7. 部署vue项目到Linux服务器

    案例一 vue-cli构建vue3项目,将项目上传到Linux服务器,服务器安装node,并启动vue项目 首先本地有一个vue项目,启动后可正常访问 本地打包后,也可直接访问 若打包后的index. ...

  8. [USACO07NOV]Cow Relays G

    题目大意 给出一张无向连通图(点数小于1000),求S到E经过k条边的最短路. 算法 这是之前国庆模拟赛的题 因为懒 所以就只挑一些题写博客 在考场上写了个dp 然后水到了50分 出考场和神仙们一问才 ...

  9. [JSC2021 A~D + F]

    半小时打完了\(A~D\),想要一发\(F\)冲进前\(100\),结果平衡树常数大\(T\)了.据说\(G\)是矩阵树定. \(A\) 放代码吧. A // code by Dix_ #includ ...

  10. [CF707 Div2, A ~ D]

    (相信进这个博客的人,都已经看过题目了,不再赘述) 这把打小号打到了\(484\),\(rating + 636\) \(A\) 考虑进行模拟就行了,说白了这是一个英语阅读题 // code by D ...