Scheduling a task in Spring MVC

In my Spring MVC application, I need to schedule a task with a specific date and time. For example, I need to schedule to send an email that will be configured dynamically by the client. Spring has the @Schedule annotation, but how can I dynamically change the value every time with any date and time.

Any help is appreciated.

+3


source to share


3 answers


You should try TaskScheduler

, see the javadoc here :



private TaskScheduler scheduler = new ConcurrentTaskScheduler();

@PostConstruct
private void executeJob() {
    scheduler.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            // your business here
        }
    }, INTERVAL);
}

      

+3


source


Refer Spring Executing and Scheduling Tasks

Annotation example

@Configuration
@EnableAsync
@EnableScheduling
public class MyComponent {

    @Async
    @Scheduled(fixedDelay=5000, repeatCount=0)
    public void doSomething() {
       // something that should execute periodically
    }
}

      

I think repeatCount = 0 will make the function execute only once (not tested yet)



Complete example with quartz scheduler http://www.mkyong.com/spring/spring-quartz-scheduler-example/

You need to enter XML config like this

<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
<task:executor id="myExecutor" pool-size="5"/>
<task:scheduler id="myScheduler" pool-size="10"/>}

      

0


source


You can easily achieve this in the standard java API by scheduling the task for the time difference between the created temporary task and the given date entered by the clients. Just specify this difference as a parameter delay

.

ScheduledThreadPoolExecutor

schedule(Callable<V> callable, long delay, TimeUnit unit)

      

Creates and runs a ScheduledFuture that fires after a specified delay.

ScheduledFuture<?>  schedule(Runnable command, long delay, TimeUnit unit)

      

Creates and executes a one-time action that fires after a specified delay.

So you have to either send Runnable or Callable for this service.

You can refer to this answer for calculating between dates:

difference in time

0


source







All Articles