Spring Boot 定时任务

Spring Boot 提供了方便的注解来实现定时任务。下面是定时任务注解的详细教程:

一、添加依赖

要使用 Spring Boot 的定时任务注解,首先需要在项目中确认已添加过spring-boot-starter的依赖。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

这个依赖会自动包含spring-context,它提供了定时任务相关的功能。

 二、开启定时任务

要开启定时任务,需要在主类上添加 @EnableScheduling 注解:

@SpringBootApplication
@EnableScheduling
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

三、创建定时任务方法

创建一个方法,并添加 @Scheduled 注解,用来表示这个方法是一个定时任务方法。

@Component
public class MyTask {

    @Scheduled(cron = "0 0 0 * * ?")
    public void myTaskMethod() {
        // 定时任务执行的代码
    }

}

@Scheduled是一个Spring框架中的注解,可以用于指定方法或者类中的方法在特定时间进行执行。它可以帮助我们轻松地编写定时任务。

@Scheduled 应用于方法上,并且支持多种参数。下面是一些常见的参数:

  • cron:按照Cron表达式来设置定时任务的执行时间
  • fixedDelay:在上一次任务执行完毕后延迟一段时间再执行下一次任务
  • fixedRate:按照固定间隔时间执行任务
  • initialDelay:表示第一次执行延迟时间

下面是一个使用 @Scheduled 注解的例子:

@Component
public class ScheduleTask {

//    @Scheduled(cron = "0/5 * * * * ?")
    @Scheduled(fixedDelay = 2000)
    public void test(){
        System.out.println(LocalDateTime.now() + "开始执行");
        try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}
        System.out.println(LocalDateTime.now() + "执行结束");
    }

}

这个例子中,ScheduleTask类被标记为 @Component,因此Spring容器会自动扫描并创建实例。然后,该类中的 test() 方法使用 @Scheduled 注解进行标记,fixedDelay=2000表示:在上一次任务执行完毕后,延迟2s再执行下一次任务。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

何苏三月

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

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

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

打赏作者

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

抵扣说明:

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

余额充值