> 文章列表 > springboot 定时任务 @Scheduled 配置文件获取cron

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

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

在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)@Beanpublic ScheduledAnnotationBeanPostProcessor processor() {return new ScheduledAnnotationBeanPostProcessor();}
}

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

public class ScheduledCondition implements Condition {@Overridepublic 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)