请结合springboot学习教程项目github地址 https://github.com/heng1234/spring-boot_one来理解
springboot整合定时任务task
启动类加上定时任务注解
//开启定时任务
@EnableScheduling
建立定时任务类
范例:
TestTask
package com.imooc.tasks;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class TestTask {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
// 定义每过3秒执行任务
// @Scheduled(fixedRate = 3000)
public void reportCurrentTime() {
System.out.println("现在时间:" + dateFormat.format(new Date()));
}
}
定时任务表达式的简单讲解与应用
SpringBoot不支持年
定时任务表达式地址: http://cron.qqe2.com/
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
// 定义每过3秒执行任务
@Scheduled(cron = "4-40 * * * * ?")
public void reportCurrentTime() {
System.out.println("现在时间:" + dateFormat.format(new Date()));
}
}