一、背景
springBoot 开启定时任务不用添加任何依赖配置,仅仅需要在 main 类上加一个 @EnableScheduling 注解即可
二、实现
2.1 添加 @EnableScheduling 注解
在 main 类上添加 @EnableScheduling 注解,如下
@SpringBootApplication
@EnableScheduling
public class Startup
{
public static void main( String[] args )
{
SpringApplication.run(Startup.class, args);
}
}
2.2 在方法上面添加 @Scheduled 注解
@Component
public class QuartzTask {
// 每分钟启动
@Scheduled(cron = "0 0/1 * * * ?")
public void timerToNow(){
System.out.println("now time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
// 每晚12点执行
@Scheduled(cron = "0 0 0 * * ?")
public void zeroTask(){
System.out.println("现在是北京时间晚上12点整!!!!!!!!!1");
}
}