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 实战》。

  • 相关阅读:
    Post与Get的区别
    线程的状态
    vsto publish后无法弹出winform窗口
    C# + winserver2008 openfiledialog 写入 textbox1 中的 路径不正确
    在 Visual C# 项目中调用 VBA 中的代码
    docker : env: /etc/init.d/redis: Permission denied
    python中常见的异常
    windows 的 docker使用
    CMD和DISM启用超级V
    升级pip
  • 原文地址:https://www.cnblogs.com/gdwkong/p/9311137.html
Copyright © 2011-2022 走看看