Springboot 使用 @Scheduled注解定时任务, 方法传参问题

      首先要理解其中机制,在你启动系统时,它和所有的bean一样加载到内存(这个时候就把需要初始化的东西全部初始完成,例如调度频率等这里就要设置好)中并做好定时任务准备。所以频率一旦初始化了再去触发修改就难以完成了。

        但有时会需要传入参数,我觉得可以通过给类加一个需要传入参数的属性,来实现传参的功能。我是在Service层实现定时任务,如需要在Controller层,记得加@component

Controller层:

 @Autowired
    private StudentTbServiceImpl studentTbService;

    @RequestMapping("findStudentById")
    public void findStudentById(int id){
        studentTbService.setId(id);
        studentTbService.findStudentById();

   }

Service层:给类加一个属性,实现get,set方法。没有参数传入。

@Scheduled(cron)参数生成可以参考:

在线Cron表达式生成器 - 码工具 (matools.com)icon-default.png?t=M666https://www.matools.com/cron/dao层用的是mybatis-plus,具体业务可以根据自己的需要来完成。

    @Autowired
    private  StudentTbMapper studentTbMapper;

    private Integer id;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Scheduled(cron = "*/10 30 10 * * ?" )
    @Override
    public StudentTb findStudentById() {
        String hourMinutes = new SimpleDateFormat("HH:mm:ss").format(new Date());
        StudentTb studentTb = studentTbMapper.selectById(this.id);
        log.info("返回数据:{}",studentTb);
        log.info("当前时间:{}",hourMinutes);
        return studentTb;
    }

SpringBoot创建定时任务,目前主要有以下三种实现方式:

  • 基于注解(@Scheduled): 基于注解@Scheduled默认为单线程,开启多个任务时,任务的执行时机会受上一个任务执行时间的影响;

  • 基于接口(SchedulingConfigurer): 用于实现从数据库获取指定时间来动态执行定时任务;

  • 基于注解设定多线程定时任务: 基于注解设定多线程定时任务;

三种实现方式,可参考:SpringBoot实现定时任务的三种方式,总有一款适合你!_Java笔记虾的博客-CSDN博客icon-default.png?t=M666https://blog.csdn.net/weixin_38405253/article/details/123748725

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,下面是一个使用 `@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` 注解,以启用定时任务功能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值