zoukankan      html  css  js  c++  java
  • Spring Boot实战笔记(七)-- Spring高级话题(计划任务)

    一、计划任务

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

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

    示例:

      1.任务计划执行类

    package com.ecworking.schedule;
    
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Service;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    @Service
    public class SchduledTaskService {
        private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    
        @Scheduled(fixedRate = 5000) // 通过@Scheduled声明该方法是计划任务,使用fixedRate属性每隔固定时间执行
        public void reportCurrentTime(){
            System.out.println("每隔五秒执行一次:" + dateFormat.format(new Date()));
        }
    
        @Scheduled(cron = "0 30 11 ? * *") // 使用cron属性可按指定时间执行计划任务,此处是11.30执行;cron是UNIX和类UNIX系统下的定时任务
        public void fixTimeExecution(){
            System.out.println("在指定时间执行:" + dateFormat.format(new Date()));
        }
    }

      2.配置类。

    package com.ecworking.schedule;
    
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.scheduling.annotation.EnableScheduling;
    
    @Configuration
    @ComponentScan("com.ecworking.schedule")
    @EnableScheduling // 通过@EnableScheduling开启对计划任务的支持
    public class SchduledTaskConfig {
    }

      3.运行。

    package com.ecworking.schedule;
    
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    public class Main {
        public static void main(String[] args){
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SchduledTaskConfig.class);
        }
    }

    运行结果:

  • 相关阅读:
    Java魔法堂:String.format详解
    Postgresql 正则表达式
    Linux下安装LAMP(Apache+PHP+MySql)和禅道
    Redis 启动警告错误解决[转]
    Postgresql: UUID的使用
    在Linux下安装RabbitMQ
    Python的包管理工具Pip
    在Linux CentOS 6.6上安装RedisLive
    [转]在Linux CentOS 6.6上安装Python 2.7.9
    在Linux上rpm安装运行Redis 3.0.4
  • 原文地址:https://www.cnblogs.com/dyppp/p/7728591.html
Copyright © 2011-2022 走看看