1、启动类上添加注解
@EnableScheduling // 开启定时任务功能
2、创建定时任务类
package com.eliancloud.ding.job;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* 获取token 任务
*
* @author :chengang
* @date :Created in 2021/11/3 10:09
*/
@Slf4j
@Component
public class GetTokenTask {
@Scheduled(cron = "*/15 * * * * ?")
public void execute() {
log.info("thread id:{},FixedPrintTask execute times:{}", Thread.currentThread().getId(),System.currentTimeMillis() );
}
}
@Scheduled(cron ="*/15 * * * * ?")注解表明这是一个需要定时执行的方法,里面的cron属性接收的是一个cron表达式,这里我给的是 */15 * * * * ? ,这个的意思是每隔15秒执行一次方法,对cron表达式不熟悉的同学可以百度一下用法。项目跑起来后可以看到方法被定时执行了:
启动一下看结果,15秒输出一次
参考学习文章:在Spring Boot中优雅的实现定时任务 - 知乎