SpringBoot框架定时任务

本文介绍了如何在SpringBoot应用中使用@Scheduled注解创建定时任务,包括fixedRate和cron表达式的使用,以及如何在启动类上启用定时任务功能。

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

在Spring Boot中,可以使用@Scheduled注解来创建定时任务。@Scheduled可以标注在方法上,用于指定方法执行的时间规则。下面是一个简单的例子:

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTasks {

    // 每隔5秒执行一次
    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        System.out.println("Current time is " + new Date());
    }

    // 每天凌晨2点执行
    @Scheduled(cron = "0 0 2 * * ?")
    public void runScheduledTask() {
        // 执行定时任务的逻辑代码
        System.out.println("Executing scheduled task...");
    }
}

在上面的示例中,我们创建了一个ScheduledTasks类,并且使用@Component注解将其标注为一个组件,以便Spring Boot能够扫描到它。然后我们在方法上使用@Scheduled注解来指定方法的执行时间规则。在第一个方法中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

加瓦程序设计师

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

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

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

打赏作者

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

抵扣说明:

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

余额充值