springboot注解添加简单的定时任务

本文详细介绍了如何在SpringBoot项目中使用定时任务,包括在项目启动类中启用定时任务,以及如何通过不同注解实现固定速率、延迟和CRON表达式的定时任务执行策略。

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

参考文章:http://blog.didispace.com/springbootscheduled/

1.项目启动类添加开启定时任务注解(@EnableScheduling)

package com.holidaylee;

import org.springframework.boot.SpringApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling
public class Application {

   public static void main(String[] args) {
      SpringApplication.run(Application.class, args);
   }
}

2.添加定时任务,注意需要添加与@Component具有相同作用的将对象交给spring容器管理的注解

package com.holidaylee.schedule;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


@Component
public class ScheduleExample {

   /**
    * 上一次开始执行时间点之后5秒再执行
    */
   @Scheduled(fixedRate = 5000)
   public void fixedRateExample(){
      System.out.println("This is a fixRate schedule example");
   }

   /**
    * 上一次执行完毕时间点之后5秒再执行
    */
   @Scheduled(fixedDelay = 5000)
   public void fixedDelayExample(){
      System.out.println("This is a fixedDelay schedule example");
   }

   /**
    * 第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
    */
   @Scheduled(initialDelay = 1000 ,fixedRate = 5000)
   public void initialDelayExample(){
      System.out.println("This is a initialDelay schedule example");
   }

   /**
    * 每天凌晨一点执行任务
    */
   @Scheduled(cron = "0 0 01 * * ?")
   public void cronExample() {
      System.out.println("This is a cron schedule example");
   }

}

注明:

本文为学习记录笔记,不喜勿喷。

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值