springBoot 开启定时任务

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、背景

        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  查看输出结果

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

快乐的小三菊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值