spring boot 执行定时任务很简单,首先只需在启动类中加入@EnableScheduling注解,
import org.springframework.boot.SpringApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.cloud.client.SpringCloudApplication;
@EnableScheduling
@SpringCloudApplication
public class DatumApplication {
/**
* 程序主方法,启动一个spring应用
*
*
* @param args
*/
public static void main(String[] args) {
SpringApplication.run(DatumApplication.class, args);
}
}
新增一个定时类,在方法上新增@Scheduled注解,定时 执行任务。
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* 定时执行任务
*
* @author hxc
*/
@Component
public class SchedulerFile {
/**
* 每天凌晨零点执行一次定时任务
* 注意定时方法不能有参数,加上参数会报错。报Only no-arg methods may be annotated with @Scheduled 错误
* @author hxc
*/
@Scheduled(cron = "0 0 0 1/1 * ?")
public void statusCheck() {
System.out.println("开始执行任务********");
//定时任务任务内容
System.out.println("结束执行任务********");
}
}