热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

springboot定时任务的快速应用

前言定时任务在我们工作中应用非常广泛,在spring中定时任务实现可以用spring自己的Scheduled实现,也可以使用第三方框架Quartz来实现

前言

定时任务在我们工作中应用非常广泛,在spring中定时任务实现可以用spring自己的 Scheduled 实现,也可以使用第三方框架 Quartz 来实现。 本文我们来看一下 Scheduled 的实现方式,通过简单的注解开启定时任务支持即可。

配置@EnableScheduling注解

  1. 我们新增一个定时的配置类,配置线程池,可选择配置拒绝策略。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
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 java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;@Configuration
@EnableScheduling
public class SchedulerTaskConfig implements SchedulingConfigurer {private static final Logger LOGGER = LoggerFactory.getLogger(SchedulerTaskConfig.class);@Overridepublic void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {scheduledTaskRegistrar.setScheduler(schedulerTheadPool());}/*** 线程池*

* @code {@Bean(destroyMethod = "shutdown")}当线程执行完毕,自动关闭线程池*

* @return*/@Bean(destroyMethod = "shutdown")public Executor schedulerTheadPool() {// 核心线程数等于运行时可用线程int coreSize = Runtime.getRuntime().availableProcessors();return new ScheduledThreadPoolExecutor(coreSize, new ThreadFactory() {@Overridepublic Thread newThread(Runnable runnable) {// 给定时任务的线程设置名字return new Thread(runnable, "scheduler-task");}}, new RejectedExecutionHandler() {// 拒绝策略@Overridepublic void rejectedExecution(Runnable runnable, ThreadPoolExecutor executor) {LOGGER.error("执行任务失败 task : {}", runnable);}});}
}

配置@Scheduled注解

  1. @Scheduled 注解支持 initialDelay 初始化延迟N毫秒执行, fixedDelay 每隔N毫秒执行一次

新增一个任务类,MyTask.java

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;@Component
public class MyTask {private static final Logger LOGGER = LoggerFactory.getLogger(MyTask.class);/*** initialDelay - 初始化时延迟5秒执行* fixedDelay - 每隔2秒执行一次*/@Scheduled(initialDelay = 5000,fixedDelay = 2000)public void execute(){LOGGER.info("==============执行定时任务 initialDelay & fixedDelay ==============");}
}

  1. 同时也支持 cron 表达式来配置更细粒度的定时任务 。 新增任务类CornTask.java 配置Corn表达式

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;@Component
public class CornTask {private static final Logger LOGGER = LoggerFactory.getLogger(CornTask.class);/*** 5 秒执行一次*/@Scheduled(cron = "0/5 * * * * *")public void execute(){LOGGER.info("==============执行定时任务 CornTask ==============");}
}

启动测试

. ____ _ __ _ _/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \\\/ ___)| |_)| | | | | || (_| | ) ) ) )' |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/:: Spring Boot :: (v2.4.1)2020-12-17 10:11:14.256 INFO 65437 --- [ main] com.lb.springboot.Application : Starting Application using Java 1.8.0_211 on yunnashengdeMacBook-Pro.local with PID 65437 (/Users/yunnasheng/work/github-workspace/springboot-scheduler-task/target/classes started by yunnasheng in /Users/yunnasheng/work/github-workspace/springboot-quickstart-002)
2020-12-17 10:11:14.258 INFO 65437 --- [ main] com.lb.springboot.Application : No active profile set, falling back to default profiles: default
2020-12-17 10:11:14.945 INFO 65437 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8002 (http)
2020-12-17 10:11:14.951 INFO 65437 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-12-17 10:11:14.951 INFO 65437 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.41]
2020-12-17 10:11:14.984 INFO 65437 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/task] : Initializing Spring embedded WebApplicationContext
2020-12-17 10:11:14.984 INFO 65437 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 694 ms
2020-12-17 10:11:15.188 INFO 65437 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8002 (http) with context path '/task'
2020-12-17 10:11:15.200 INFO 65437 --- [ main] com.lb.springboot.Application : Started Application in 1.144 seconds (JVM running for 1.558)
2020-12-17 10:11:20.001 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.CornTask : ==============执行定时任务 CornTask ==============
2020-12-17 10:11:20.197 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============执行定时任务 initialDelay & fixedDelay ==============
2020-12-17 10:11:21.201 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============执行定时任务 initialDelay & fixedDelay ==============
2020-12-17 10:11:22.206 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============执行定时任务 initialDelay & fixedDelay ==============
2020-12-17 10:11:23.211 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============执行定时任务 initialDelay & fixedDelay ==============
2020-12-17 10:11:24.216 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============执行定时任务 initialDelay & fixedDelay ==============
2020-12-17 10:11:25.001 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.CornTask : ==============执行定时任务 CornTask ==============
2020-12-17 10:11:25.220 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============执行定时任务 initialDelay & fixedDelay ==============
2020-12-17 10:11:26.225 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============执行定时任务 initialDelay & fixedDelay ==============
2020-12-17 10:11:27.227 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============执行定时任务 initialDelay & fixedDelay ==============
2020-12-17 10:11:28.229 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============执行定时任务 initialDelay & fixedDelay ==============
2020-12-17 10:11:29.235 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============执行定时任务 initialDelay & fixedDelay ==============
2020-12-17 10:11:30.001 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.CornTask : ==============执行定时任务 CornTask ==============
2020-12-17 10:11:30.237 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============执行定时任务 initialDelay & fixedDelay ==============
2020-12-17 10:11:31.243 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============执行定时任务 initialDelay & fixedDelay ==============
2020-12-17 10:11:32.245 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============执行定时任务 initialDelay & fixedDelay ==============
2020-12-17 10:11:33.250 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============执行定时任务 initialDelay & fixedDelay ==============
2020-12-17 10:11:34.256 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============执行定时任务 initialDelay & fixedDelay ==============
2020-12-17 10:11:35.001 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.CornTask : ==============执行定时任务 CornTask ==============
2020-12-17 10:11:35.262 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============执行定时任务 initialDelay & fixedDelay ==============
2020-12-17 10:11:36.267 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============执行定时任务 initialDelay & fixedDelay ==============
2020-12-17 10:11:37.268 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============执行定时任务 initialDelay & fixedDelay ==============
2020-12-17 10:11:38.270 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============执行定时任务 initialDelay & fixedDelay ==============
2020-12-17 10:11:39.271 INFO 65437 --- [ scheduler-task] com.lb.springboot.task.MyTask : ==============执行定时任务 initialDelay & fixedDelay ==============

demo案例源码: https://github.com/yunnasheng/springboot-scheduler-task.git



推荐阅读
  • Spring学习(4):Spring管理对象之间的关联关系
    本文是关于Spring学习的第四篇文章,讲述了Spring框架中管理对象之间的关联关系。文章介绍了MessageService类和MessagePrinter类的实现,并解释了它们之间的关联关系。通过学习本文,读者可以了解Spring框架中对象之间的关联关系的概念和实现方式。 ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • 本文介绍了一个Java猜拳小游戏的代码,通过使用Scanner类获取用户输入的拳的数字,并随机生成计算机的拳,然后判断胜负。该游戏可以选择剪刀、石头、布三种拳,通过比较两者的拳来决定胜负。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • 本文介绍了如何在给定的有序字符序列中插入新字符,并保持序列的有序性。通过示例代码演示了插入过程,以及插入后的字符序列。 ... [详细]
  • 本文讨论了在Spring 3.1中,数据源未能自动连接到@Configuration类的错误原因,并提供了解决方法。作者发现了错误的原因,并在代码中手动定义了PersistenceAnnotationBeanPostProcessor。作者删除了该定义后,问题得到解决。此外,作者还指出了默认的PersistenceAnnotationBeanPostProcessor的注册方式,并提供了自定义该bean定义的方法。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • [大整数乘法] java代码实现
    本文介绍了使用java代码实现大整数乘法的过程,同时也涉及到大整数加法和大整数减法的计算方法。通过分治算法来提高计算效率,并对算法的时间复杂度进行了研究。详细代码实现请参考文章链接。 ... [详细]
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • r2dbc配置多数据源
    R2dbc配置多数据源问题根据官网配置r2dbc连接mysql多数据源所遇到的问题pom配置可以参考官网,不过我这样配置会报错我并没有这样配置将以下内容添加到pom.xml文件d ... [详细]
  • 深入理解Kafka服务端请求队列中请求的处理
    本文深入分析了Kafka服务端请求队列中请求的处理过程,详细介绍了请求的封装和放入请求队列的过程,以及处理请求的线程池的创建和容量设置。通过场景分析、图示说明和源码分析,帮助读者更好地理解Kafka服务端的工作原理。 ... [详细]
  • Android系统源码分析Zygote和SystemServer启动过程详解
    本文详细解析了Android系统源码中Zygote和SystemServer的启动过程。首先介绍了系统framework层启动的内容,帮助理解四大组件的启动和管理过程。接着介绍了AMS、PMS等系统服务的作用和调用方式。然后详细分析了Zygote的启动过程,解释了Zygote在Android启动过程中的决定作用。最后通过时序图展示了整个过程。 ... [详细]
  • 本文介绍了Python语言程序设计中文件和数据格式化的操作,包括使用np.savetext保存文本文件,对文本文件和二进制文件进行统一的操作步骤,以及使用Numpy模块进行数据可视化编程的指南。同时还提供了一些关于Python的测试题。 ... [详细]
author-avatar
静静敲代码
很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有