计划任务
在我看来就是隔一段时间去执行某个操作,这里我们简单做了一个报告当前时间的案例来理解并使用计划任务
效果
如何实现?
- 创建一个计划任务类
package com.example.springboot1;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class ScheduledTasks {
//获取log日志对象用于输出log日志
private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
/**
* 日志中报告当前时间的方法
*/
@Scheduled(fixedDelay = 5000) //定义计划任务 这里的参数fixedDelay 表示任务完成开始测量两次调用之间的间隔
public void reportCurrentTime(){
log.info("This time is now {}",dateFormat.format(new Date()));
}
}
配置好计划任务类中的两个注解之后, 给application类加入以下注解
@EnableScheduling
package com.example.springboot1;
import com.example.controller.GreetingController;
import com.example.controller.Hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling //设置允许springboot 运行后台计划任务
public class Springboot1Application {
public static void main(String[] args) {
SpringApplication.run(Springboot1Application.class, args);
}
}