Java – how to disable the @ scheduled method through the properties file?
•
Java
I have a spring reservation method that runs regularly:
@Scheduled(cron = "${spring.cron.expression}") public void demonJob() throws .. { .. }
From application Properties successfully read cron expression:
spring.cron.expression=0 0 * * * *
Now, I want to deploy my application to a special environment where this specific scheduled method should not run If I leave the cron attribute blank like this
spring.cron.expression=
.. I get the following exception:
Encountered invalid @Scheduled method 'demonJob': Cron expression must consist of 6 fields (found 0 in "")
How to gracefully disable the scheduled method, ideally only in application Different settings are provided in properties?
Solution
Empty string is an incorrect cron expression If you want to disable the scheduler under certain conditions, just use the @ profile annotation, or if you must operate on a property, use the @ conditionalonproperty annotation in spring boot
@Component @ConditionalOnProperty(prefix = "spring.cron",name = "expression") public class MyScheduler { @Scheduled(cron = "${spring.cron.expression}") public void demonJob() throws .. { .. } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码