这一篇中,实现一个简单的功能:定时任务。
实现这个功能主要用到3个注解:@Component,@Scheduled,@EnableScheduling。
其中@Component表示这个类是一个组件可以被Spring容器自动检测扫描到;@Scheduled表示这个方法是个定时任务方法,同时可以配置定时参数;@EnableScheduling表示会创建后台执行器,去执行定时任务。
下面写一个小demo,每隔1秒钟打印当前的时间。
package com.spring.hello;
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;
/**
* Created by zhangyi on 2017/3/30.
*/
@Component
public class ScheduledTasks {
private static final Logger log= LoggerFactory.getLogger(ScheduledTasks.class);
private static final SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 1000) //fixedRate这个参数表示每隔多少毫秒执行一次,1000也就是1000毫秒=1秒
public void reportCurrentTime(){
log.info("Current time is {}",sdf.format(new Date()));
}
}
package com.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* Created by zhangyi on 2017/3/29.
*/
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
启动之后,就可以在控制台看到输出了,每隔1秒钟打印一次当前时间