一、背景
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");
}
}
2.3 查看输出结果

本文介绍如何在SpringBoot中轻松实现定时任务。通过在主类上添加@EnableScheduling注解激活定时任务支持,并使用@Scheduled注解定义具体任务。文中详细展示了如何设置不同频率的任务执行计划。
1375

被折叠的 条评论
为什么被折叠?



