springboot 定时任务 @Scheduled 配置文件获取cron

文章介绍了如何在SpringBoot中配置定时任务,包括通过@Scheduled注解启动任务,从application.yml读取cron表达式,以及如何通过开关控制所有定时任务的开启和关闭,涉及到ScheduledAnnotationBeanPostProcessor的条件化创建。

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

在Application启动类上加上 @EnableScheduling ,在类上加上@Component,在方法上加上@Scheduled,就可以启动一个定时任务。

1.定时任务启动

@Slf4j
@EnableScheduling
@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
        log.info(">>>>>>>>>>>>>>>>>>>>>>>启动完成<<<<<<<<<<<<<<<<<<<<<<<");
    }
}
@Component
public class MyTask {
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Scheduled(cron = "* * * * * ?")
    public void t1(){
        System.out.println(sdf.format(new Date()));
    }
}

 以上是将定时任务的时间写死在了代码里。

2.通过配置文件获取cron时间

如果要将时间写在application.yml,如下

#application.yml中的配置

myScheduled:
  myCron: * * * * * ?
@Scheduled(cron = "${myScheduled.myCron}")
public void t1(){
    System.out.println(sdf.format(new Date()));
}

3.关闭定时任务

Spring Boot 2.1 以上的版本,在 cron 中使用 "-"  。

#application.yml中的配置

myScheduled:
  myCron: "-"

#注意:在yml文件中,-需要用双引号,因为在yml文件中 - 是特殊符号,代表list。在properties文件中,不需要双引号

是否可以写未来的一个时间,例如2099年,这样在有生之年他都不会执行了。但@Scheduled 不识别年。

4.通过开关来控制定时任务

 加一个开关,来控制所有的定时任务是否开启。

原理:

加了@Scheduled的方法之所以被执行,是因为被 ScheduledAnnotationBeanPostProcessor 这个类拦截。而这个类是由@EnableScheduling 生成。源码如下:


@Import({SchedulingConfiguration.class})
public @interface EnableScheduling {
}

//EnableScheduling注解有个@Import({SchedulingConfiguration.class}),SchedulingConfiguration的源码如下,
//他干了个事 new ScheduledAnnotationBeanPostProcessor()

@Configuration
public class SchedulingConfiguration {
//... 为了减少空间 我省略了其他代码
    public ScheduledAnnotationBeanPostProcessor scheduledAnnotationProcessor() {
        return new ScheduledAnnotationBeanPostProcessor();
    }
}

所以,我们控制所有的定时任务是否开启,就需要自己来创建ScheduledAnnotationBeanPostProcessor,即首先要去掉启动类上的@EnableScheduling

然后再通过@Configuration和@Bean来创建ScheduledAnnotationBeanPostProcessor,@Conditional这个注解是用来判断true还是false,即开关的作用。

@Configuration
public class ScheduledConfig {
//@Conditional判断ScheduledCondition获取到值是true还是false,true则创建bean

    @Conditional(ScheduledCondition.class)
    @Bean
    public ScheduledAnnotationBeanPostProcessor processor() {
        return new ScheduledAnnotationBeanPostProcessor();
    }
}

 @Conditional(ScheduledCondition.class)中的ScheduledCondition,用来获取配置文件中的值

public class ScheduledCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //读取配置中的属性
        return Boolean.valueOf(context.getEnvironment().getProperty("myEnable.myScheduled"));
    }
}
#application.yml中的配置

myEnable:
  myScheduled: true

参考

https://segmentfault.com/a/1190000018805591

ruoyi项目的quartz模块,有专门的定时任务工具类,通过数据库配置定时任务,修改定时任务状态,可以在后台管理工具中手动切换,重启,执行任务。

RuoYi: 🎉 基于SpringBoot的权限管理系统 易读易懂、界面简洁美观。 核心技术采用Spring、MyBatis、Shiro没有任何其它重度依赖。直接运行即可用 (gitee.com)

=====================分割线======================== 

文章到这里已经结束,以下是紫薯布丁

@Slf4j
@EnableScheduling
@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
        log.info(">>>>>>>>>>>>>>>>>>>>>>>启动完成<<<<<<<<<<<<<<<<<<<<<<<");
    }
}

@Component
public class MyTask {
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Scheduled(cron = "* * * * * ?")
    public void t1(){
        System.out.println(sdf.format(new Date()));
    }
}

#application.yml中的配置

myScheduled:
  myCron: * * * * * ?

@Scheduled(cron = "${myScheduled.myCron}")
public void t1(){
    System.out.println(sdf.format(new Date()));
}

#application.yml中的配置

myScheduled:
  myCron: "-"

#注意:在yml文件中,-需要用双引号,因为在yml文件中 - 是特殊符号,代表list。在properties文件中,不需要双引号


@Import({SchedulingConfiguration.class})
public @interface EnableScheduling {
}

//EnableScheduling注解有个@Import({SchedulingConfiguration.class}),SchedulingConfiguration的源码如下,
//他干了个事 new ScheduledAnnotationBeanPostProcessor()

@Configuration
public class SchedulingConfiguration {
//... 为了减少空间 我省略了其他代码
    public ScheduledAnnotationBeanPostProcessor scheduledAnnotationProcessor() {
        return new ScheduledAnnotationBeanPostProcessor();
    }
}

@Configuration
public class ScheduledConfig {
//@Conditional判断ScheduledCondition获取到值是true还是false,true则创建bean

    @Conditional(ScheduledCondition.class)
    @Bean
    public ScheduledAnnotationBeanPostProcessor processor() {
        return new ScheduledAnnotationBeanPostProcessor();
    }
}

public class ScheduledCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //读取配置中的属性
        return Boolean.valueOf(context.getEnvironment().getProperty("myEnable.myScheduled"));
    }
}

#application.yml中的配置

myEnable:
  myScheduled: true

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

globalcoding

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

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

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

打赏作者

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

抵扣说明:

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

余额充值