Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC 3 Time scheduled task starting at a specific time

I want to schedule a method call in Spring MVC to run after every two hours. This I can easily do via Spring 3.0 Time Scheduler. However, I want to kick the execution off only at a specific time of the day. That is, the method should only be invoked every 2 hours starting at a particular time.

For example - I want the method to run every 2 hours starting 6 AM. The TimeScheduler interface has a scheduleAtFixedRate method which is overloaded to use startTime Date argument. I am not really sure how to use this.

Any idea how this can be achieved ?

like image 933
Tushar Avatar asked Dec 01 '25 17:12

Tushar


1 Answers

You could take a look at the TaskScheduler interface. It provides a method scheduleAtFixedRate(Runnable task, Date startTime, long period) which returns a ScheduledFuture. You can use this with some simple Spring configuration:

<task:scheduler id="scheduler" pool-size="10"/>

This will create an instance of ThreadPoolTaskScheduler which implements TaskScheduler. Wire this bad boy into the class to call your specific method:

public class MyClass {
    @Autowired
    private TaskScheduler scheduler;

    public void init() {
        scheduler.scheduleAtFixedRate(new Runnable() {
            public void run() {
                myMethod();
            }
        }, new Date(), 1000 * 60 * 60 * 2); //This will start now and run every two hours
    }

    public void myMethod() {
        // the method you want to invoke
    }
}
like image 85
nicholas.hauschild Avatar answered Dec 05 '25 02:12

nicholas.hauschild



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!