sping的@Scheduled只能是常量如:
 @Scheduled(cron = "1 3 0 * * ? ")

若想动态改变其值需要继承SchedulingConfigurer,如下:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@EnableScheduling
public class XXXSchedule implements SchedulingConfigurer {

    private Logger logger = LoggerFactory.getLogger(IndexCloseSchedule.class);

    private String cronConfig() {
        String cronTabExpression = "0 50 3 * * ? ";
        if (timeOfCloseIndex != null) {
            cronTabExpression = "0 50 4 * * ? ";
        }
        return cronTabExpression;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(new Runnable() {

            @Override
            public void run() {
                //do something
            }
        },new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                String cron = cronConfig();
                logger.info(cron);
                CronTrigger trigger = new CronTrigger(cron);
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;
            }
        });
    }
}


更多推荐

spring 动态schedule