How to call a method after some specific interval of time in Java
Here is the use case:
I am using Java (with Spring)
Once the user (through a web-app) confirms to the subscription, I want to send him an email exactly af开发者_运维知识库ter 30 mins.
Now how to do this? Do I need a message broker? or something like ScheduledExecutorService? Do I need some sort of queue?
Please advise.
Can look into quartz scheduler for this.
By the way a common strategy is to send a bulk of all pending mails in bulk in every 30 minutes or so. Quartz can help in do that as well.
You can use the Quartz Scheduler. Its fairly easy to use. You can schedule something every week or ever 30 minutes or whatever you want basically.
Create an object for Timer
private Timer myTimer;
in main method
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
//your method
}
}, 0, 200);
It is not that the thread will die after sending the mail. When you configure Quartz, a new thread will automatically be created and will execute the assigned task on specified interval. Or else you use Timer class also. It is very easy to use.
Timer timer = new Timer(); // Get timer
long delay = 30 * 60 * 1000; // 3o min delay
// Schedule the two timers to run with different delays.
timer.schedule(new MyTask(), 0, delay);
...................
class MyTask extends TimerTask {
public void run() {
// business logic
// send mail here
}
}
精彩评论