首页 > 编程语言 > 详细

SpringBoot中定时任务的设置

时间:2019-12-26 15:01:50      阅读:66      评论:0      收藏:0      [点我收藏+]

1.注解:@EnableScheduling  用在SpringBoot项目中的启动类上,表示开启对定时任务的支持;@PropertySource(value = {"file:application.properties"})  读取指定的外部配置,和jar包同级目录;

package com.keenyoda.datacollector;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
@SpringBootApplication
@EnableScheduling
@PropertySource(value = {"file:application.properties"})
public class DataCollectorApplication {

    public static void main(String[] args) {
        SpringApplication.run(DataCollectorApplication.class, args);
    }
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();

    }


}

2.注解:@Scheduled  中有以下几个参数:

  1>.cron是设置定时执行的表达式,如 0 0/5 * * * ?每隔五分钟执行一次 秒 分 时 天 月

每隔5秒执行一次:"*/5 * * * * ?"

每隔1分钟执行一次:"0 */1 * * * ?"

每天23点执行一次:"0 0 23 * * ?"

每天凌晨1点执行一次:"0 0 1 * * ?"

每月1号凌晨1点执行一次:"0 0 1 1 * ?"

每月最后一天23点执行一次:"0 0 23 L * ?"

每周星期天凌晨1点实行一次:"0 0 1 ? * L"

在26分、29分、33分执行一次:"0 26,29,33 * * * ?"

每天的0点、13点、18点、21点都执行一次:"0 0 0,13,18,21 * * ?"

表示在每月的1日的凌晨2点调度任务:"0 0 2 1 * ? *"

表示周一到周五每天上午10:15执行作业:"0 15 10 ? * MON-FRI" 

表示2002-2006年的每个月的最后一个星期五上午10:15执行:"0 15 10 ? 6L 2002-2006"

  2>.zone表示执行时间的时区

  3>.fixedDelay 和fixedDelayString 表示一个固定延迟时间执行,上个任务完成后,延迟多长时间执行

  4>.fixedRate 和fixedRateString表示一个固定频率执行,上个任务开始后,多长时间后开始执行

  5>.initialDelay 和initialDelayString表示一个初始延迟时间,第一次被调用前延迟的时间

注:这里详细说明一下 fixedRate  和 fixedRateString 的区别,fixedRate  =[final 修饰的一个常量];fixedRateString =[一个字符串];当考虑时间可以在项目中自定义设置,我们一般会采取读配置文件来获取设置的时间

具体实现代码如下:

1.fixedRate 没有办法使用外部配置注入时间

//@value("${TIME}") 是无效的
private final int TIME=6000;
    
    @Scheduled(fixedRate = TIME)
    public void testScheduledUsed(){
        System.out.println("这是一个定时任务");
    }

2.fixedRateString 可以使用外部配置注入时间

    @Scheduled(fixedRateString = "${TIME}")
    public void testScheduledUsed(){
        System.out.println("这是一个定时任务");
    }

配置文件  application.properties 

TIME=5000

SpringBoot中定时任务的设置

原文:https://www.cnblogs.com/wdzhz/p/12101729.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!