springBoot 定时器任务

1、新建一个计划任务类(只能和主类平级或在主类的下级) 

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指定从

  完成任务测量的时间间隔。还可以指定具体时间,使用 Scheduled(cron="... ")

  cron参数说明: 0 0 10,14,16 * * ? 每天上午10点,下午2点,4点

  0 0/30 9-17 * * ?   朝九晚五工作时间内每半小时

  0 0 12 ? * WED 表示每个星期三中午12点 
  "0 0 12 * * ?" 每天中午12点触发

  其中 按顺序依次为:

    秒(0~59)

    分钟(0~59)

    小时(0~23)

    天(月)(0~31,但是你需要考虑你月的天数)

    月(0~11)

    天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)

    7.年份(1970-2099)

 

2、启用定时任务

 当上面一切被设置好之后,还需要在主类中加入 @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);
	}
}

 3、启动,当一切编译完毕时,可以启动来测试了,在类中右键-->RunAs-->SpringBoot App,一切正常就会看到如下结果

 

猜你喜欢

转载自www.cnblogs.com/cyrfr/p/9165591.html
今日推荐