SpringBoot 系列实战 | 第二篇: SpringBoot项目整合定时器注解版的使用@Scheduled(cron = “0 0 0 * * * “)

SpringBoot 系列实战 | 第二篇: SpringBoot项目整合定时器注解版的使用@Scheduled(cron = “0 0 0 * * * “)

一、第一种方法
1.1 全局的配置在主启动类上添加注解@EnableScheduling开启定时器总开关

@SpringBootApplication
@EnableScheduling
public class CustomerApplication {

    public static void main(String[] args) {
        SpringApplication.run(CustomerApplication.class, args);
    }
}

1.2 给指定的方法上添加定时任务注解@Scheduled(cron = "0 0 0 * * * ") 没1分钟执行一次

    @Scheduled(cron = "0 */1 * * * ?")
    @GetMapping(value = "getTest")
    public String getTest(){
        String test = testFeign.getTest();
        logger.info("getTest-feign消费者调用提供者返回数据:"+test);
        return test;
    }

在这里插入图片描述在这里插入图片描述结论:定时任务1分钟执行一次,验证成功。

二、第二种方法
2.1、直接在定时器类上添加@Configuration、@EnableScheduling注解,标注这个类是配置文件,并开启定时开关
2.2、给要定时执行方法上添加@Scheduled(cron = "0 0 0 * * * ")

package com.customer.configuration;

import com.customer.feign.TestFeign;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;

@Configuration     //证明这个类是一个配置文件
@EnableScheduling  //启用定时器
public class EnableSchedulingCofig {

    private static final Logger logger = LoggerFactory.getLogger(EnableSchedulingCofig.class);
    
    @Autowired
    private TestFeign testFeign;

    @Scheduled(cron = "0 */1 * * * ?")
    @GetMapping(value = "getTest")
    public String getTest(){
        String test = testFeign.getTest();
        logger.info("getTest-feign消费者调用提供者返回数据:"+test);
        return test;
    }
    
}

在这里插入图片描述在这里插入图片描述结论:定时任务1分钟执行一次,验证成功

2.3、在线Cron表达式生产器 https://qqe2.com/cron
Cron表达式
格式: cron = [秒] [分] [小时] [日] [月] [周] [年]

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值