How to conditionally enable or disable scheduled jobs in Spring?

The most efficient way to disable @Scheduled in Spring is to set cron expression to -

@Scheduled(cron = "-")
public void autoEvictAllCache() {
    LOGGER.info("Refresing the Cache Start :: " + new Date());
    activeMQUtility.sendToTopicCacheEviction("ALL");
    LOGGER.info("Refresing the Cache Complete :: " + new Date());
}

From the docs:

CRON_DISABLED

public static final String CRON_DISABLED
A special cron
expression value that indicates a disabled trigger: “-“. This is
primarily meant for use with ${…} placeholders, allowing for
external disabling of corresponding scheduled methods.

Since:
5.1 See Also: ScheduledTaskRegistrar.CRON_DISABLED

Leave a Comment