Java实现定时执行任务Springboot的Scheduled
@Component
public class ScheduledTasks {
private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
//下面的任务每隔5000毫秒,即每隔5秒执行一次。
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
log.info("使用fixedRate执行定时任务,当前时间 {}", dateFormat.format(new Date()));
}
//下面的任务每隔3秒开始
@Scheduled(cron = "0/3 * * * * ?")
public void reportCurrentTimeByCron() {
log.info("使用cron表达式执行定时任务,当前时间 {}", dateFormat.format(new Date()));
}
}
二,在启动类中必须
@SpringBootApplication
@EnableScheduling
public class GeneralSpringBootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(GeneralSpringBootDemoApplication.class, args);
}
}
的注解@EnableScheduling
浙公网安备 33010602011771号