使用SpringBoot创建定时任务非常简单,目前主要有以下三种创建方式:

一、基于注解(@Scheduled)
二、基于接口(SchedulingConfigurer) 前者相信大家都很熟悉,但是实际使用中我们往往想从数据库中读取指定时间来动态执行定时任务,这时候基于接口的定时任务就派上用场了。
三、基于注解设定多线程定时任务

一、静态:基于注解

1、创建定时器

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

@Component
@Configuration //主要用于标记配置类,兼备component的效果
@EnableScheduling //开启定时任务
public class StaticScheduleTask { @Resource
RealTimeMonitorServiceImpl realTimeMonitorService; //添加定时任务 4小时/4小时/4小时/
@Scheduled(cron = "0 0 0/4 * * ?")
private void configureTasks() {
log.info("执行静态定时任务时间: " + LocalDateTime.now()); } }

关于Cron表达式介绍

cronExpression定义时间规则,Cron表达式由6或7个空格分隔的时间字段组成:秒 分钟 小时 日期 月份 星期 年(可选)

字段  允许值  允许的特殊字符 
秒       0-59     , - * / 
分       0-59     , - * / 
小时      0-23     , - * / 
日期      1-31     , - * ? / L W C 
月份      1-12     , - * / 
星期      1-7       , - * ? / L C # 
年     1970-2099   , - * /

表达式网站生成:   http://cron.qqe2.com/

二、动态:基于接口

基于接口(SchedulingConfigurer)

<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、添加数据库记录:

开启本地数据库mysql,随便打开查询窗口,然后执行脚本内容,如下:

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.yml 添加数据源:

spring:
datasource:
url: jdbc:mysql://localhost:3306/socks
username: root
password: 123456

3、创建定时器

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

@Component
@Configuration //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class DynamicScheduleTask implements SchedulingConfigurer { @Mapper
public interface CronMapper {
@Select("select cron from cron limit 1")
public String getCron();
} @Autowired //注入mapper
@SuppressWarnings("all")
CronMapper cronMapper; /**
* 执行定时任务.
*/
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.addTriggerTask(
//1.添加任务内容(Runnable)
() -> System.out.println("执行动态定时任务: " + LocalDateTime.now().toLocalTime()),
//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);
}
);
} }

三、多线程定时任务

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

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();
}
}

代码地址:https://github.com/mmzsblog/springboot-schedule

转载:https://www.cnblogs.com/mmzs/p/10161936.html

springboot项目 @Scheduled注解 实现定时任务的更多相关文章

  1. springboot 基于@Scheduled注解 实现定时任务

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

  2. Spring 的@Scheduled注解实现定时任务运行和调度

    Spring 的@Scheduled注解实现定时任务运行和调度 首先要配置我们的spring.xml   ---  即spring的主配置文件(有的项目中叫做applicationContext.xm ...

  3. Spring Boot 使用 @Scheduled 注解创建定时任务

    在项目开发中我们经常需要一些定时任务来处理一些特殊的任务,比如定时检查订单的状态.定时同步数据等等. 在 Spring Boot 中使用 @Scheduled 注解创建定时任务非常简单,只需要两步操作 ...

  4. Spring Boot入门(三):使用Scheduled注解实现定时任务

    在程序开发的过程中,经常会使用定时任务来实现一些功能,比如: 系统依赖于外部系统的非核心数据,可以定时同步 系统内部一些非核心数据的统计计算,可以定时计算 系统内部的一些接口,需要间隔几分钟或者几秒执 ...

  5. 使用轻量级Spring @Scheduled注解执行定时任务

    WEB项目中需要加入一个定时执行任务,可以使用Quartz来实现,由于项目就一个定时任务,所以想简单点,不用去配置那些Quartz的配置文件,所以就采用了Spring @Scheduled注解来实现了 ...

  6. 基于 @Scheduled 注解的 ----定时任务

    最常用的方法@Scheduled 注解表示起开定时任务 依赖 <dependencies> <dependency> <groupId>org.springfram ...

  7. 使用spring提供的@Scheduled注解创建定时任务

    使用方法 操作非常简单,只要按如下几个步骤配置即可 1. 导入jar包或添加依赖,其实定时任务只需要spring-context即可,当然起服务还需要spring-web: 2. 编写定时任务类和方法 ...

  8. spring @Scheduled注解执行定时任务

    以前框架使用quartz框架执行定时调度问题. 这配置太麻烦.每个调度都需要多加在spring的配置中. 能不能减少配置的量从而提高开发效率. 最近看了看spring的 scheduled的使用注解的 ...

  9. quartz 框架定时任务,使用spring @Scheduled注解执行定时任务

    配置quartz 在spring中需要三个jar包: quartz-1.6.5.jar.commons-collections-3.2.jar.commons-logging-1.1.jar 首先要配 ...

随机推荐

  1. 1120day-户别确认

    1.实体类 package com.edu.empity; public class People { private String hubie; private String livetype; p ...

  2. 【刷题-LeetCode】307. Range Sum Query - Mutable

    Range Sum Query - Mutable Given an integer array nums, find the sum of the elements between indices ...

  3. .Net Core依赖注入

    一.配置文件的读取 利用Startup类中的configuration读取appsettings.json中的配置 { "Logging": { "LogLevel&qu ...

  4. 基于SpringBoot如何实现一个点赞功能?

    基于SpringBoot如何实现一个点赞功能? 解析: 基于 SpringCloud, 用户发起点赞.取消点赞后先存入 Redis 中,再每隔两小时从 Redis 读取点赞数据写入数据库中做持久化存储 ...

  5. 哪些是GET请求,哪些是POST请求

    GET请求: 1,form标签 method=get 2,a标签 3,link标签引入css 4,Script标签引入js文件 5,img标签引入图片 6,iframe引入html页面 7,在浏览器地 ...

  6. IoC容器-Bean管理注解方式(完全注解开发)

    完全注解开发 (1)创建配置类,替代xml配置文件 (2)编写测试类 在实际中一般用springboot做

  7. One Switch

    前言 One Switch 是由国内知名开发者 TualatriX 带来的最新作品,功能小巧精简,设计优雅,犹如一块多功能的遥控器,通过状态栏快捷菜单即可「一键」快速实现保持亮屏.切换 AirPods ...

  8. 《手把手教你》系列技巧篇(六十一)-java+ selenium自动化测试 - 截图三剑客 -下篇(详细教程)

    1.简介 按照计划宏哥今天将介绍java+ selenium自动化测试截图操作实现的第三种截图方法,也就是截图的第三剑客 - 截取某个元素(或者目标区域)的图片.在测试的过程中,有时候不需要截取整个屏 ...

  9. 使用VSCode在本地电脑上对树莓派远程开发

    目的及原理 有时身边没有额外的显示器和键盘,或者有时树莓派在另一个屋子连接着路由器,那么当我们想在树莓派上做开发时就可以使用VS Code的远程开发能力.下面一张图显而易见地说明了远程开发的工作原理( ...

  10. python11day

    昨日回顾 函数的参数: 实参角度:位置参数.关键字参数.混合参数 形参角度:位置参数.默认参数.仅限关键字参数.万能参数 形参角度参数顺序:位置参数,*args,默认参数,仅限关键字参数,**kwar ...