zoukankan      html  css  js  c++  java
  • Spring boot @EnableScheduling 和 @Scheduled 注解使用例子

    前言

    Spring Boot提供了@EnableScheduling @Scheduled注解,用于支持定时任务的执行,那么接下来就让我们学习下如何使用吧;

    假设我们需要每隔10秒执行一个任务,那么我们可以按一下步骤来完成开发;

    添加@EnableScheduling注解

    在Spring Boot的启动类上添加@EnableScheduling注解,@EnableScheduling属于Spring Context 模块的注解,其内部通过@Import(SchedulingConfiguration.class)注解引入了SchedulingConfiguration

    添加注解代码示例如下:

    @SpringBootApplication
    @EnableScheduling
    public class SpringBootWebApplication {
         
    }
    

    添加@Scheduled注解

    接下来我们就可以在需要执行定时任务的方法上添加@Scheduled注解了,前提条件是该方法不能有参数;

    对于每一个没有参数的方法,添加@Scheduled注解后,都会被默认的线程池按计划执行;
    代码示例:

    @Scheduled(initialDelay = 1000, fixedRate = 10000)
    public void run() {
        logger.info("Current time is :: " + Calendar.getInstance().getTime());
    }
    

    控制台输出:

    2017-03-08 15:02:55 - Current time is :: Wed Mar 08 15:02:55 IST 2017
    2017-03-08 15:03:05 - Current time is :: Wed Mar 08 15:03:05 IST 2017
    2017-03-08 15:03:15 - Current time is :: Wed Mar 08 15:03:15 IST 2017
    2017-03-08 15:03:25 - Current time is :: Wed Mar 08 15:03:25 IST 2017
    2017-03-08 15:03:35 - Current time is :: Wed Mar 08 15:03:35 IST 2017
    
  • 相关阅读:
    stack2
    xctf 实时数据监测
    note-service2
    stack pivot学习
    sctf_2019_easy_heap 利用off-by-null构造出double free来向任一地址写入(经典)
    ciscn_2019_s_1 unlink或者of-by-null
    starctf_2019_babyshell 绕过循环检测注入shellcode
    sublime 安装package control
    windows上安装nodejs,升级npm,安装webpack指南
    mysql 常见语句
  • 原文地址:https://www.cnblogs.com/chenpi/p/9785953.html
Copyright © 2011-2022 走看看