Spring Boot定时任务

Spring boot 定时任务#

开启定时任务注解##

@SpringBootApplication(scanBasePackages = "org.mxn.sample")
@MapperScan("org.mxn.sample.sampledao.mapper")
@ServletComponentScan
@EnableTransactionManagement  //开启事务
@EnableScheduling //开启任务调度
public class SampleWebApplication {

    public static void main(String[] args) {
        SpringApplication.run(SampleWebApplication.class, args);
    }

}

编写定时任务##

@Component
public class ScheduledTasks {

    public static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);

    /**
     * 通过在方法上加@Scheduled注解,表明该方法是一个调度任务
     * @Scheduled(fixedRate = 5000) :上一次开始执行时间点之后5秒再执行
     * @Scheduled(fixedDelay = 5000) :上一次执行完毕时间点之后5秒再执行
     * @Scheduled(initialDelay=1000, fixedRate=5000) :第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
     * @Scheduled(cron="0/3 * * * * ? ") :通过cron表达式定义规则,在线定义获取cron表达式 http://www.bejson.com/othertools/cron/
     */

    @Scheduled(cron = "0/3 * * * * ? ")
    public void reportCurrentTime(){
		//打印当前时间
        logger.info("ScheduledTasks.reportCurrentTime info:" + DateHelper.datetime(new Date(), DateHelper.DEFAULT_DATETIME_FORMAT));
    }
}
有志者,事竟成,破釜沈舟,百二秦关终属楚。苦心人,天不负,卧薪尝胆,三千越甲可吞吴。
原文地址:https://www.cnblogs.com/menxn/p/10830405.html