Spring中如何定一个计划任务呢?
今天接到一个需求,需在Spring中实现一个计划任务,可以定时运行程序,那么该如何实现呢?
下文笔者将一一道来,如下所示
下文笔者将一一道来,如下所示
实现思路:
1.编写一个计划任务配置类,并加上注解@EnableScheduling
2.在计划任务的运行方法上加上注解 @Scheduled
@Scheduled使用场景
使用@Scheduled支持多种类型的计划任务 如:cron、fixDelay、fixRate等
@Scheduled示例
1.修改配置类
添加注解@EnableScheduling
package com.java265.schedule;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* 说明:配置类
*/
@Configuration
@EnableScheduling
public class ScheduleConfiguration {
}
//计划任务运行类
package com.java265.schedule;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 说明:计划任务执行类
*/
@Service
public class ScheduleTaskService {
private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("HH:mm:ss");
/**
* 通过@Scheduled声明该方法是计划任务
* fixedRate设置任务按照固定时间间隔执行
*/
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
System.out.println(String.format("每隔5秒执行一次 " + SIMPLE_DATE_FORMAT.format(new Date())));
}
/**
* 使用cron设置任务在指定时间执行
* 下例指的是每天11点28分执行。
*/
@Scheduled(cron = "0 28 11 ? * *")
public void fixTimeExecution() {
System.out.println("在指定的时间 " + SIMPLE_DATE_FORMAT.format(new Date() + "执行"));
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


