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);
    }
}

运行结果:

原文地址:https://www.cnblogs.com/dyppp/p/7728591.html