SpringBoot系列:Spring Boot定时任务Spring Schedule

Spring Schedule是Spring提供的定时任务框架,相较于Quartz,Schedule更加简单易用,在中小型应用中,对于大部分需求,Schedule都可以胜任。

一、Spring Schedule使用演示

在SpringBoot使用Spring Schedule非常简单,因为SpringBoot自身的starter中已经集成了Schedule,而不需要我们做更多的处理。

使用@EnableScheduling注解开启定时功能,该注解可以使用在启动类上,也可以注解于定时任务的类上。然后使用@Scheduled注解配合其参数完成定时任务。

例如我们需要每一秒执行一次的任务, 写成@Scheduled(fixedRate = 1000)即可。

@EnableScheduling

@Component

public class Task {

private static final SimpleDateFormat dateFormat = new SimpleDateFormat(“HH:mm:ss”);

@Scheduled(fixedRate = 1000)

public void taskOne(){

System.out.println(“现在时间:” dateFormat.format(new Date()));

}

}

启动程序,该定时就可以间隔一秒持续执行了。

你可能感兴趣的:(spring,spring,boot,java)