Home > Java > javaTutorial > How to Dynamically Schedule Jobs with a Fixed Rate in Spring?

How to Dynamically Schedule Jobs with a Fixed Rate in Spring?

DDD
Release: 2024-11-27 20:21:11
Original
375 people have browsed it

How to Dynamically Schedule Jobs with a Fixed Rate in Spring?

How to Schedule a Job with Spring Programmatically with Dynamically Set Fixed Rate

In Spring, tasks can be scheduled using annotations like @Scheduled. However, if the fixed rate needs to be changed dynamically without redeploying the application, a different approach is required.

One solution is to use a Trigger. With a trigger, you can calculate the next execution time on the fly based on a custom logic.

Here's an example of how to configure a trigger-based job using the ScheduledTaskRegistrar:

@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)); //Get the value dynamically
                        return nextExecutionTime.getTime();
                    }
                }
        );
    }
}
Copy after login

This allows you to set the fixed rate dynamically using the Environment property. The myRate property can be retrieved from any source, such as a database or a configuration file.

The above is the detailed content of How to Dynamically Schedule Jobs with a Fixed Rate in Spring?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template