一、新建一个计划任务类(只能和主类平级或在主类的下级) php
import java.text.SimpleDateFormat; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class ScheduledTasks { private static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class); private static final SimpleDateFormat dataFromat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 1000) public void reportCurrent(){ logger.info("如今时间:{}",dataFromat.format(new Date())); } }
本示例中使用的是 fixedRate函数,它指定的是从调用开始时间到指定时间以后,单位毫秒。还有 fixedDelay指定从java
完成任务测量的时间间隔。还能够指定具体时间,使用 Scheduled(cron="... ")spring
cron参数说明: 0 0 10,14,16 * * ? 天天上午10点,下午2点,4点函数
0 0/30 9-17 * * ? 朝九晚五工做时间内每半小时测试
0 0 12 ? * WED 表示每一个星期三中午12点
"0 0 12 * * ?" 天天中午12点触发orm
其中 按顺序依次为:blog
秒(0~59)get
分钟(0~59)io
小时(0~23)编译
天(月)(0~31,可是你须要考虑你月的天数)
月(0~11)
天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)
7.年份(1970-2099)
二、启用定时任务
当上面一切被设置好以后,还须要在主类中加入 @EnableScheduling 注解来启动任务,不然定时任务不会被执行
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @EnableScheduling //必须加此注解 public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
三、启动,当一切编译完毕时,能够启动来测试了,在类中右键-->RunAs-->SpringBoot App,一切正常就会看到以下结果