每次执行后,请更改@Schduled批注中的cron值

时间:2019-02-14 13:57:42

标签: java spring spring-boot

如何在每次执行方法cron后动态更改execute的值

@Component
@EnableScheduling
public class PendingOrderScheduler {

    private final Logger logger;
    private final OrderService orderService;

    public PendingOrderScheduler(Logger logger, OrderService orderService) {
        this.logger = logger;
        this.orderService = orderService;
    }

    @Scheduled(cron = "*/1 * * * * *")
    public void execute() {
        logger.info(String.format("Executed at %s", new Date()));
        this.orderService.updatePendingOrder();
    }
}

2 个答案:

答案 0 :(得分:2)

如果您想在运行时配置作业调度,我认为您不能使用@Scheduled注释。您可以使用spring documentation.

中所述的定制调度程序

要更改配置,您需要取消当前计划并使用任务计划程序的Future对象创建新计划。

答案 1 :(得分:0)

不幸的是,在cron中更改cron是不可能的。

您可以使用SchedulingConfigurer来实现,但是@Scheduled注释将被删除。

@Component
@EnableScheduling
public class PendingOrderScheduler implements SchedulingConfigurer{

    private Map<String,CronTask> cronTasks = new HashMap<>();

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setTaskScheduler(taskScheduler());
        this.taskRegistrar = taskRegistrar;
        addCronTask();
    }

    private CronTask addCronTask(){
        CronTask task = new CronTask(new Runnable() {
            public void run() {
                logger.info(String.format("Executed at %s", new Date()));
                this.orderService.updatePendingOrder();
            }
        }, "*/1 * * * * *"); //read it from some variable
        cronTasks.put("CRON_KEY", task);
        return task;
    }

    public void changeCron(){ //call it when you whant to change chron
        synchronized (PendingOrderScheduler.class) {
            List<CronTask> crons = taskRegistrar.getCronTaskList();
            taskRegistrar.destroy(); //important, cleanups current scheduled tasks
            taskRegistrar.setCronTasksList(new ArrayList<CronTask>());
             for (CronTask cron : crons) {
                if (!cronTasks.containsValue(cron)) {
                    taskRegistrar.addCronTask(cron); //copy croned by @Scheduled tasks as is
                }
            }               
            addCronTask();
            taskRegistrar.afterPropertiesSet(); //rebuild
        }
    }   
}

此外,您还可以查看支持cron更改的Quartz库。