本文共 1109 字,大约阅读时间需要 3 分钟。
SpringBoot添加定时任务非常简单,只需要两步即可
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.scheduling.annotation.EnableScheduling;/** *描述:springboot启动类
*/@SpringBootApplication@EnableScheduling // 开启定时任务的配置public class DemoApp { public static void main(String[] args) { // 整个程序入口,启动springboot项目 SpringApplication.run(DemoApp.class, args); }}
注意在类上不要少了注解,要执行的方法上也不能少了注解,@Scheduled的使用方法请找度娘
import java.text.SimpleDateFormat;import java.util.Date;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;@Componentpublic class TaskTest { //输出时间格式 private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); // 第一次执行前延时5秒启动,每次任务结束后15秒再次启动 @Scheduled(initialDelay = 5000, fixedDelay = 15000) private void sayHello() { System.out.println(format.format(new Date())+"向宇宙发出了一声问候:Hello World!"); }}
转载于:https://blog.51cto.com/1197822/2295894