我使用@Scheduled
注释在Spring中定义具有cron样式模式的预定作业.
cron模式存储在配置属性文件中.实际上有两个属性文件:一个默认配置,一个依赖于环境的配置文件配置(例如dev,test,prod customer 1,prod customer 2等)并覆盖一些默认值.
我在spring上下文中配置了一个属性占位符bean,它允许我使用${}
样式占位符从我的属性文件中导入值.
作业bean看起来像这样:
@Component
public class ImagesPurgeJob implements Job {
private Logger logger = Logger.getLogger(this.getClass());
@Override
@Transactional(readOnly=true)
@Scheduled(cron = "${jobs.mediafiles.imagesPurgeJob.schedule}")
public void execute() {
//Do something
//can use DAO or other autowired beans here
}
}
Run Code Online (Sandbox Code Playgroud)
我的上下文XML的相关部分:
<!-- Enable configuration of scheduled tasks via annotations -->
<task:annotation-driven/>
<!-- Load configuration files and allow '${}' style placeholders -->
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config/default-config.properties</value>
<value>classpath:config/environment-config.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="ignoreResourceNotFound" …
Run Code Online (Sandbox Code Playgroud) 有没有办法创建一个cron表达式,根本不运行该作业.我虽然使用这个表达式:
0 0 0 1 1?3099
上面的表达式将在3099年运行.有没有其他方法可以禁用该作业.
谢谢.
我有一个定期运行的Spring计划方法:
@Scheduled(cron = "${spring.cron.expression}")
public void demonJob() throws .. { .. }
Run Code Online (Sandbox Code Playgroud)
cron表达式已成功读取application.properties
:
spring.cron.expression=0 0 * * * *
Run Code Online (Sandbox Code Playgroud)
现在,我想将我的应用程序部署到一个特殊的环境,在该环境中不应该运行这个特定的Scheduled方法.如果我像这样将cron属性留空
spring.cron.expression=
Run Code Online (Sandbox Code Playgroud)
..我得到以下异常:
Encountered invalid @Scheduled method 'demonJob': Cron expression must consist of 6 fields (found 0 in "")
Run Code Online (Sandbox Code Playgroud)
如何优雅地禁用Scheduled方法,理想情况下只能通过提供不同的设置application.properties
?
我的应用程序从属性文件加载了一些cron模式。我使用这样的@Scheduled
注释:
@Scheduled(cron = "${config.cronExpression:0 0 11,23 * * *}")
现在我想禁用一些任务,最简单的解决方案是输入永远不会运行的cron模式。为此,我考虑过使用仅在过去特定日期执行的cron表达式。但不幸的是,Spring cron表达式不允许在过去添加年份或日期。
有没有永远不会运行的模式?
我正在调查以固定速率使用@Scheduled的情况,在某些可配置的情况下,不应运行计划的作业。
该文档没有提及这一点,而是分别针对fixedDelay()
和fixedDelayString()
是-1
和的默认值""
。可以使用这些方法可靠地确保计划的方法不会触发吗?