Search code examples
javaspring-bootschedule

How to schedule executing method for certain time during runtime


Lets say I have some rest api where arguments are time when to execute method and second argument is name of the method in class. What is the best way for invoking call of this method in certain time (just once) in spring-boot application ?


Solution

  • First, enable scheduling in your spring-boot application:

    @SpringBootApplication
    @EnableScheduling
    public class Application {
    // ...
    

    Then, inject the TaskScheduler bean and schedule the task programmatically every time the user invokes the REST method:

    public class MyScheduler {
    
        @Autowired
        private TaskScheduler scheduler;
    
        public void scheduleNewCall(Date dateTime) {
            scheduler.schedule(this::scheduledMethod, dateTime);
        }
    
        public void scheduledMethod() {
        // method that you wish to run
        }
    
    }
    
    

    However, you should also think about limiting the amount of calls to this method, otherwise the malicious user could schedule a lot of tasks and overflow the task pool.