How to conditionally enable or disable scheduled jobs in Spring?

前端 未结 11 1383
轻奢々
轻奢々 2020-11-28 07:26

I am defining scheduled jobs with cron style patterns in Spring, using the @Scheduled annotation.

The cron pattern is stored in a config properties file

11条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 07:49

    @Component
    public class CurrencySyncServiceImpl implements CurrencySyncService {
    
        private static Boolean isEnableSync;
        /**
         * Currency Sync FixedDelay in minutes
         */
        private static Integer fixedDelay;
    
        @Transactional
        @Override
        @Scheduled(fixedDelayString = "#{${currency.sync.fixedDelay}*60*1000}")
        public void sync() {
            if(CurrencySyncServiceImpl.isEnableSync) {
                //Do something
                //you can use DAO or other autowired beans here.
            }
        }
    
        @Value("${currency.sync.fixedDelay}")
        public void setFixedDelay(Integer fixedDelay) {
            CurrencySyncServiceImpl.fixedDelay = fixedDelay;
        }
    
        @Value("${currency.sync.isEnable}")
        public void setIsEnableSync(Boolean isEnableSync) {
            CurrencySyncServiceImpl.isEnableSync = isEnableSync;
        }
    }
    

提交回复
热议问题