zoukankan      html  css  js  c++  java
  • Springboot学习笔记(二)-定时任务

    springboot中要使用定时任务需要在配置类或启动类上标注注解@EnableScheduling,并在定时执行的无参方法上标注注解@Scheduled,程序启动后会根据@Scheduled所提供的信息定时执行。

    Scheduled参数

    参数名 含义
    cron = "* * * * * ?" 每秒执行
    zone 时区,默认为本地时区TimeZone.getDefault()
    fixedDelay = 1000 上次任务执行完成后1秒开始
    fixedDelayString = "1000" 等同fixedDelay = 1000
    fixedRate = 1000 每秒执行
    fixedRateString = "1000" 等同fixedRate = 1000
    initialDelay = 1000 初始延时1秒执行
    initialDelayString = "1000" 等同initialDelay = 1000

    cron表达式

    不用记,网上有在线cron生成器

    **String

    公司规定的代码规范中不允许使用魔法数字,可以用这些参数规避。

    代码

    @Component
    public class ScheduledHelloTask {
        private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledHelloTask.class);
    
        private int getSecond() {
            return Calendar.getInstance().get(Calendar.SECOND);
        }
    
        // 每秒执行
        @Scheduled(cron = "* * * * * ?", zone = "Asia/Shanghai")
        public void sayHello() {
            LOGGER.info("Hello World!");
        }
    
        // 任务执行完成后延时1秒开始
        @Scheduled(fixedDelay = 1000)
        public void sayHello1() throws InterruptedException {
            LOGGER.info(getSecond() + "春暖花开~");
            Thread.sleep(1000);
        }
    
        // 每秒执行,效果等同{cron = "* * * * * ?"}
        @Scheduled(initialDelay = 2000, fixedRate = 1000)
        public void sayHello2() throws InterruptedException {
            LOGGER.info(getSecond() + "你好~");
        }
    }
    

    关闭

    有时候我们在得到自己需要的结果后想关闭定时任务,比如通过前台发送链接来开启上面的打印Hello World!任务,希望它执行10次后关闭。
    此时就不能在类ScheduledHelloTask上添加@Component了, 因为我们需要动态注册bean来实现。改造如下:

    @EnableScheduling
    public class ScheduledHelloTask {
        private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledHelloTask.class);
        private AtomicInteger atomicInteger = new AtomicInteger();
    
        public AtomicInteger getAtomicInteger() {
            return atomicInteger;
        }
    
        public void setAtomicInteger(AtomicInteger atomicInteger) {
            this.atomicInteger = atomicInteger;
        }
    
        // 每秒执行
        @Scheduled(cron = "* * * * * ?", zone = "Asia/Shanghai")
        public void sayHello() {
            int count = atomicInteger.incrementAndGet();
            LOGGER.info("第" + count + "次:Hello World!");
        }
    }
    

    添加ScheduleController,代码如下:

    @RestController
    public class ScheduleController {
        private static final String BEAN_NAME = "scheduledHelloTask";
    
        @GetMapping
        public String sayHi() throws InterruptedException {
            AnnotationConfigApplicationContext applicationContext =
                    new AnnotationConfigApplicationContext();
            if (!applicationContext.containsBean(BEAN_NAME)) {
                applicationContext.register(ScheduledHelloTask.class);
            }
            applicationContext.refresh();
            while (applicationContext.containsBean(BEAN_NAME)) {
                if (applicationContext.getBean(ScheduledHelloTask.class).getAtomicInteger().get() == 10) {
                    applicationContext.removeBeanDefinition(BEAN_NAME);
                }
            }
            return "success";
        }
    }
    

    两次访问localhost:8080,结果如下:

    预期效果已实现!

  • 相关阅读:
    LENGTH()和CHAR_LENGTH()区别
    使用ibatis时 sql中 in 的参数赋值(转)
    数据库类型空间效率探索(五)- decimal/float/double/varchar
    MySQL用命令行复制表的方法
    升讯威微信营销系统开发实践:微信接口的 .NET 封装
    Github开源:Sheng.RabbitMQ.CommandExecuter (RabbitMQ 的命令模式实现)
    开源 & 免费使用 & 打包下载自行部署 :升讯威 周报系统
    开源 & 免费使用 & 打包下载自行部署 :升讯威 周报系统
    GitHub开源:升讯威ADO.NET增强组件 sheng.ADO.NET.Plus V1.3
    [源代码] SailingEase .NET Resources Tool (.NET 多语言资源编辑器)
  • 原文地址:https://www.cnblogs.com/yw0219/p/8976125.html
Copyright © 2011-2022 走看看