1.Application文件
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* Created by guanguan on 17/5/31.
*/
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
}
2.定时任务ScheduledTasks文件
package hello;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by guanguan on 17/5/31.
*/
@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) //表示间隔时间为5s,即为每5s执行一次
public void reportCurrentTime(){
log.info("The time is now{} ",dateFormat.format(new Date()));
System.out.println("hello ");
}
}
3.此例子中采用了fixedRate,当然也可用cron
-
"0 0 * * * *" = the top of every hour of every day.表示每天的整点数执行一次 "*/10 * * * * *" = every ten seconds. 表示每间隔10s执行一次 "0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.表示每天的8:00,9:00,10:00执行 "0 0 6,19 * * *" = 6:00 AM and 7:00 PM every day.表示每天的上午6点,下午7点执行 "0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day.表示每天的8点到10点时间段内每隔30分钟执行一次 "0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays 表示周一到周五的9:00到下午5:00每整点数执行一次 "0 0 0 25 12 ?" = every Christmas Day at midnight 表示12月25号零点执行一次
共6个字段,分别代表秒、分、时、天、月、星期或者年
字段 允许值 允许的特殊字符
秒 0-59 , - * /
分 0-59 , - * /
小时 0-23 , - * /
日期 1-31 , - * ? / L W C
月份 1-12 或者 JAN-DEC , - * /
星期 1-7 或者 SUN-SAT , - * ? / L C #
年(可选) 留空, 1970-2099 , - * /
- 区间
* 通配符
? 你不想设置那个字段