Scheduling a job with Spring programmatically (wit

2019-01-02 17:22发布

问题:

Currently I have this :

@Scheduled(fixedRate=5000)
public void getSchedule(){
   System.out.println("in scheduled job");
}

I could change this to use a reference to a property

@Scheduled(fixedRate=${myRate})
public void getSchedule(){
   System.out.println("in scheduled job");
}

However I need to use a value obtained programmatically so the schedule can be changed without redeploying the app. What is the best way? I realize using annotations may not be possible...

回答1:

Using a Trigger you can calculate the next execution time on the fly.

Something like this should do the trick (adapted from the Javadoc for @EnableScheduling):

@Configuration
@EnableScheduling
public class MyAppConfig implements SchedulingConfigurer {

    @Autowired
    Environment env;

    @Bean
    public MyBean myBean() {
        return new MyBean();
    }

    @Bean(destroyMethod = "shutdown")
    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(100);
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());
        taskRegistrar.addTriggerTask(
                new Runnable() {
                    @Override public void run() {
                        myBean().getSchedule();
                    }
                },
                new Trigger() {
                    @Override public Date nextExecutionTime(TriggerContext triggerContext) {
                        Calendar nextExecutionTime =  new GregorianCalendar();
                        Date lastActualExecutionTime = triggerContext.lastActualExecutionTime();
                        nextExecutionTime.setTime(lastActualExecutionTime != null ? lastActualExecutionTime : new Date());
                        nextExecutionTime.add(Calendar.MILLISECOND, env.getProperty("myRate", Integer.class)); //you can get the value from wherever you want
                        return nextExecutionTime.getTime();
                    }
                }
        );
    }
}


回答2:

Also you can use this simple approach:

private int refreshTickNumber = 10;
private int tickNumber = 0; 

@Scheduled(fixedDelayString = "${some.rate}")
public void nextStep() {
    if (tickNumber < refreshTickNumber) {
        tickNumber++;
        return;
    }
    else {
        tickNumber = 0;
    }
    // some code
}

refreshTickNumber is fully configurable at runtime and can be used with @Value annotation.



回答3:

you can manage restarting scheduling using TaskScheduler and ScheduledFuture :

@Configuration
@EnableScheduling
@Component
public class CronConfig implements SchedulingConfigurer , SchedulerObjectInterface{

    @Autowired
    private ScheduledFuture<?> future;

     @Autowired
        private TaskScheduler scheduler;

    @Bean
    public SchedulerController schedulerBean() {
        return new SchedulerController();
    }

    @Bean(destroyMethod = "shutdown")
    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(100);
    } 

        @Override
    public void start() {
        future = scheduler.schedule(new Runnable() {
            @Override
            public void run() {
                //System.out.println(JOB + "  Hello World! " + new Date());
                schedulerBean().schedulerJob();
            }
        }, new Trigger() {
            @Override public Date nextExecutionTime(TriggerContext triggerContext) {
                Calendar nextExecutionTime =  new GregorianCalendar();
                Date lastActualExecutionTime = triggerContext.lastActualExecutionTime(); 
           nextExecutionTime.setTime(convertExpresssiontoDate());//you can get the value from wherever you want
                return nextExecutionTime.getTime();
            }
        });

    }


    @Override
    public void stop() {
        future.cancel(true);

    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        // TODO Auto-generated method stub
        start();
    }

}

interface for start stop :

public interface SchedulerObjectInterface {    
    void start();
    void stop();
}

now you can stop and start again (restarting) Scheduling using @Autowired SchedulerObjectInterface



标签: