在springboot
项目中如何使用定时任务,其实很简单,只需要两步
1、在springboot启动类添加注解@EnableScheduling开启对定时任务的支持
package com.che.pri;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2、创建定时任务类,在需要定时执行的方法上添加注解@Scheduled
package com.che.pri.task;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class TestTask {
@Scheduled(cron = "0 0/1 * * * ?")
public void testTask() {
System.out.println("执行了定时任务");
}
}
注意
,此处定时任务类TestTask
,必需添加@Component
,或其他声明为spring组件的注解