zoukankan      html  css  js  c++  java
  • SpringBoot -- 计划任务

       从Spring 3.1 开始,计划任务在Spring中的实现变得异常的简单。首先通过在配置类注解@EnableScheduling 来开启对计划任务的支持,然后再执行集合任务的方法上注解@Scheduled,声明这是一个计划任务。

      Spring通过@Scheduled支持多种类的计划任务,包含cron、fixDelay、fixRate等。

    一、计划任务执行类

    package com.cenobitor.scheduler.taskscheduler;
    
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Service;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    
    @Service
    public class ScheduledTaskService {
        private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("HH:mm:ss");
    
        @Scheduled(fixedRate = 5000)//1
        public void reportCurrentTime(){
            System.out.println("每隔五秒执行一次 "+DATE_FORMAT.format(new Date()));
        }
    
        @Scheduled(cron = "0 02 22 ? * *")//
        public void fixTimeExecution(){
            System.out.println("在指定时间 "+DATE_FORMAT.format(new Date())+"执行");
        }
    }

    1、通@Sceduled声明该方法是计划任务,使用fixedRate属性每隔固定时间执行。

    2、使用cron属性可按照指定时间执行,本例指每天22点02分执行。

    二、运行

    package com.cenobitor.scheduler;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.scheduling.annotation.EnableScheduling;
    
    @SpringBootApplication
    @EnableScheduling
    public class SchedulerApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SchedulerApplication.class, args);
        }
    }

      使用@EnableScheduling注解开启对计划任务的支持。

    运行结果:

    每隔五秒执行一次 22:01:54
    每隔五秒执行一次 22:01:59
    在指定时间 22:02:00执行
    每隔五秒执行一次 22:02:04

      注:摘抄自《JavaEE开发的颠覆者SpringBoot 实战》。

  • 相关阅读:
    js中的标签运动
    js的窗口坐标及拖拽
    js中滑动门的实现方法和案例
    js中的键盘事件和触摸事件
    JavaScript中的鼠标事件
    JavaScript中DOM操作之获取元素占位
    JavaScript中DOM操作之设定标签属性
    JavaScript中DOM操作文档对象模型获取标签内容
    windows10下python安装+selenium
    主体数据管理
  • 原文地址:https://www.cnblogs.com/gdwkong/p/9311137.html
Copyright © 2011-2022 走看看