springboot实现定时任务 基于@Scheduled注解
在平常的开发工作中,我们经常会用到定时任务,比如定时刷新数据,定时去执行某个业务操作,定时任务,我们经常使用,那么springboot可以怎样实现定时任务呢?
1:创建定时任务:方法上添加@Scheduled注解,定义执行频率,如@Scheduled(fixedRate = 1000)
@Component
public class ScheduledTask {
@Scheduled(fixedRate = 1000)
public void scheduledTest() {
// 打印时间
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println(sdf.format(new Date()));
}
}
2:创建启动类:在启动类上面添加@EnableScheduling注解,配置在启动类上,开启对计划任务的支持。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class SpringbootApplicationTest {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplicationTest.class, args);
}
}
3:启动项目:看控制台打印时间
@Scheduled注解参数说明
