这篇文章将介绍怎么经过spring去作调度任务。java
建立一个Springboot工程,在它的程序入口加上@EnableScheduling,开启调度任务。spring
@SpringBootApplication @EnableScheduling public class SpringbootSchedulingTasksApplication { public static void main(String[] args) { SpringApplication.run(SpringbootSchedulingTasksApplication.class, args); } }
建立一个定时任务,每过5s在控制台打印当前时间。springboot
@Component public class ScheduledTasks { private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class); private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 5000) public void reportCurrentTime() { log.info("The time is now {}", dateFormat.format(new Date())); } }
经过在方法上加@Scheduled注解,代表该方法是一个调度任务。架构
启动springboot工程,控制台没过5s就打印出了当前的时间。分布式
2017-04-29 17:39:37.672 INFO 677 — [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is now 17:39:37 2017-04-29 17:39:42.671 INFO 677 — [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is now 17:39:42 2017-04-29 17:39:47.672 INFO 677 — [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is now 17:39:47 2017-04-29 17:39:52.675 INFO 677 — [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is now 17:39:52
Spring Cloud大型企业分布式微服务云构建的B2B2C电子商务平台源码请加企鹅求求:一零三八七七四六二六 微服务