当前位置: 首页 > news >正文

Springboot定时任务开发

1.使用@EnableScheduling注解开启定时任务,

2.在需要定时执行的方法上添加@Scheduled(cron = "* * * * * ?")注解,

3.将定时任务放到Spring容器中进行管理 @Component

cron表达式,从左到右分别表示:秒 分 时 日 月 周 

各个属性允许的值,参照下图

 可通过在线cron表达式生成定时任务的时间

在线Cron表达式生成器

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 定时任务
 *  1.@EnableScheduling 开启定时任务
 *  2.@Scheduled  开启一个定时任务
 */
@EnableScheduling
@Slf4j
@Component
@EnableAsync
public class HelloSchedule {

    @Resource
    ThreadPoolExecutor threadPoolExecutor;

    /**
     * 1.spring中由6位组成,不包括第七位的年
     * 2.在周几的位置,1~7表示周一到周日
     * 3.定时任务不应该阻塞。默认是阻塞的
     *      1)可以让其他业务的运行以异步的方式执行。即调用CompletableFuture.runAsync()方法解决
     *      2)反过来,可以让定时任务以异步的方式执行
     *          a)在“类”上面添加注解:  @EnableAsync
     *          b)给希望异步执行的方法上标注: @Async
     *      解决:使用异步+定时任务来完成定时任务不阻塞
     */
    @Async
    @Scheduled(cron = "* * * * * ?")
    public void hello(){
        log.info("hello.....");
        CompletableFuture.runAsync(()->{
            //xxServiceImpl.doSomething()
        },threadPoolExecutor);
    }
}

上面的代码中在类名上使用@EnableAsync开启异步编程,在要异步执行的方法上使用@Async开启异步执行。

http://www.dtcms.com/a/113493.html

相关文章:

  • Java 大视界 -- Java 大数据在智能医疗远程护理与患者健康管理中的应用与前景(175)
  • 游戏引擎学习第205天
  • infinityfree最新免费建站详细教程_无需备案_5G空间_无限流量_免费域名_免费SSL
  • [巴黎高师课程] 同步反应式系统(2024-2025)第三课 - Kind 2: 基于SMT的Lustre模型检查器
  • 快速解决 Java 服务 CPU 过高问题指南
  • Tomcat的部署
  • 泡棉压缩对显示模组漏光的定位分析及论述
  • C 语言函数四(递归)
  • Node.js核心模块及Api详解
  • 【Block总结】PlainUSR的局部注意力,即插即用|ACCV2024
  • Synopsys:设计对象
  • Scade One - 可视化编程体验
  • 如何高效使用 Ubuntu 中文官方网站
  • 【含文档+PPT+源码】基于Python的股票数据可视化及推荐系统的设计与实现
  • MobileDet(2020➕CVPR)
  • Unity:销毁(Destroy)
  • Qt多线程从基础到性能优化
  • 尚硅谷2019版多线程以及枚举类笔记记录
  • 量化交易----从0到1
  • 【开题报告+论文+源码】基于SpringBoot+Vue的爱家园管理系统
  • 一天一个java知识点----多线程
  • 虚拟Ashx页面,在WEB.CONFIG中不添加handlers如何运行
  • Linux系统之chkconfig命令详解
  • P1036 [NOIP 2002 普及组] 选数(DFS)
  • LeetCode算法题(Go语言实现)_32
  • 详解七大排序
  • 什么是RPC通信
  • 【spring cloud Netflix】Ribbon组件
  • 供应链业务-供应链全局观(二)
  • 蓝桥云客--回文数组