springboot 使用 @Scheduled注解定时任务, 方法传参解决办法

  • 如题,springboot使用定时任务很简单,加个注解就行啦 

注解的使用方法,1.启动类加上注解 @EnableScheduling //开启定时任务支持

                         2.方法上使用@Scheduled(cron = "0 0 3 * * ?") 这个代表每天凌晨三点启动, cron具体使用请百度

                         3.如果不是在service层使用定时任务,要注意你的方法要加载到spring里面, 请使用@component

 

  • 然后就是加了定时任务的方法怎么传参, 比如有个方法, 我需要获取日期,一般是获取当天的时间new Date()就行了
  • 但是,有时候我需要自己传一个日期进来, 如下操作

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
好的,下面是一个使用 `@Scheduled` 注解实现定时任务的 Spring Boot 示例代码: 首先,在 Spring Boot 项目的 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> ``` 然后,在一个 Spring Boot 的 Java 类中添加以下代码: ```java import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class ScheduledTasks { @Scheduled(fixedRate = 5000) // 每隔 5 秒执行一次 public void task1() { System.out.println("Task1: " + System.currentTimeMillis()); } @Scheduled(cron = "0 0/1 * * * ?") // 每分钟执行一次 public void task2() { System.out.println("Task2: " + System.currentTimeMillis()); } } ``` 上面代码中,我们使用 `@Scheduled` 注解来实现两个定时任务,一个是每隔 5 秒执行一次,另一个是每分钟执行一次。 其中,`@Scheduled` 注解有两个常用的属性: - `fixedRate`:表示任务执行的间隔时间,单位为毫秒。 - `cron`:表示基于 Cron 表达式的定时任务配置,格式为 `second minute hour dayOfMonth month dayOfWeek year`。 最后,启动 Spring Boot 应用程序,即可看到定时任务在后台自动执行的输出结果。 注意:在 Spring Boot 应用程序中使用 `@Scheduled` 注解时,需要在应用程序主类上添加 `@EnableScheduling` 注解,以启用定时任务功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值