springboot1学习(五)创建定时任务

本文探讨了在SpringBoot中使用@Scheduled注解创建定时任务的常见实践,强调了在分布式环境中考虑幂等性和容错机制的重要性,并介绍了项目中通常不直接采用此方式,而是倾向于使用专业任务调度平台。
摘要由CSDN通过智能技术生成

使用@Scheduled注解

在Spring Boot的主类中加入@EnableScheduling注解,启用定时任务的配置

新建schedule包,新建ScheduledTasks.java

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

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class ScheduledTasks {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    //Execute the annotated method with a fixed period between invocations.
    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        //执行任务调度方法:
        System.out.println("现在时间:" + dateFormat.format(new Date()));
    }
}

测试结果
在这里插入图片描述

但是项目中一般不这么用,分布式架构会产生幂等性问题,大项目都有专门的任务调度平台

其次函数执行失败没有容错机制

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值