zoukankan      html  css  js  c++  java
  • Spring Boot 配置定时任务

    package com.zooper.demo;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    @Component
    public class ScheduledTasks {
        private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
    
        private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    
        /**
         * 每隔5秒执行一次
         */
        @Scheduled(fixedRate = 5000)
        public void reportCurrentTime() {
            log.info("The time is now {}", dateFormat.format(new Date()));
        }
    
        /**
         * 根据cron表达式格式触发定时任务
         *  cron表达式格式:
         *      1.Seconds Minutes Hours DayofMonth Month DayofWeek Year
         *      2.Seconds Minutes Hours DayofMonth Month DayofWeek 
         *  顺序:
         *      秒(0~59)
         *      分钟(0~59)
         *      小时(0~23)
         *      天(月)(0~31,但是你需要考虑你月的天数)
         *      月(0~11)
         *      天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)
         *      年份(1970-2099)
         * 
         *  注:其中每个元素可以是一个值(如6),一个连续区间(9-12),一个间隔时间(8-18/4)(/表示每隔4小时),一个列表(1,3,5),通配符。
         *  由于"月份中的日期"和"星期中的日期"这两个元素互斥的,必须要对其中一个设置?.
         */
        @Scheduled(cron="5 * * * * ?")
        public void cronScheduled() {
            log.info("cron : The time is now {}", dateFormat.format(new Date()));
        }
    }

    启用定时任务

    package com.zooper.demo;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.scheduling.annotation.EnableScheduling;
    
    @SpringBootApplication
    @EnableScheduling
    public class Application {
    
        public static void main(String[] args) throws Exception {
            SpringApplication.run(Application.class);
        }
    }
  • 相关阅读:
    Python简介
    开博啦
    关于ajax访问跨域问题
    关于PHP empty()函数的错误理解
    if判断 和&&
    元素和节点
    详解js和jquery里的this关键字
    document.body的一些用法以及js中的常见问题
    浏览器报错显示
    getAttribute()获取属性
  • 原文地址:https://www.cnblogs.com/ThinkVenus/p/8040596.html
Copyright © 2011-2022 走看看