Spring Boot 中配置定时任务

1. 启动类上添加@EnableScheduling注解开启定时任务支持

@EnableScheduling
@SpringBootApplication
public class TestScheduledApplication extends SpringBootServletInitializer {

 @Override 
 protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
  return builder.sources(this.getClass());
 }

 public static void main(String[] args) {
  new SpringApplicationBuilder(TestScheduledApplication.class).web(true).run(args);
 }
}

2.配置定时方法

添加@Component扫描本类,在方法上添加@Scheduled注解声明定时任务,配置时间周期

@Component
public class TestTask1 {
 private static final Logger logger = LogManager.getLogger();

 // 间隔1秒执行一次
 @Scheduled(cron = "0/1 * * * * ?")
 public void method1() {
  logger.info("——————————method1 start——————————");
  logger.info("——————————method1 end——————————");
 }
}

转载:

经验分享 程序员 微信小程序 职场和发展