Reputation: 517
I am writing a bulkmailer application, here The application will send multiple mails one by one.
The following code is to send the bulk mails one by one
for(MailRecieversDTO individualObject: dto) {
bulkMailSender.sendSimpleMessage(individualObject);
try {
TimeUnit.MINUTES.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
There sendSimpleMessage()
method will send the message. I want to send emails at 5 minutes intervals.
For that I have used TimeUnit.MINUTES.sleep(5);
.
In this case it is working fine as I am directly configuring the time here as 5 minutes. Now I need to send the time for sleep() method from client screen(angular).
For the first request of send bulk mail it will work fine with the provided time. If the second call come to send another bulk mail with the different time then the time gets changed with the new one.
In this case the method is going to change like below
public void sendMail(int time, dto){
for(MailRecieversDTO individualObject: dto) {
bulkMailSender.sendSimpleMessage(individualObject);
try {
TimeUnit.MINUTES.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
My question is I want to take time gap from client and send the mails with the time gap provided from the front end. if the second request comes to send another mail then the first thread will continue executing first mails with the first provided time gap and second mail also continue with the second provided time.
Can I achieve with TimeUnit.MINUTES.sleep(time);
or is there any other alternative way.
Upvotes: 2
Views: 187
Reputation: 7792
Class ScheduledExecutorService fits your purposes by far better. It takes a task and repeats it at the scheduled time intervals for you and you don't have to worry about the exception handling. If you want to change the time interval you just stop the service you are running and re-schedule it with a new time interval.
Also if you feel more adventurous, you can check an alternative background task runner that is part of the MgntUtils Open source library (written by me). Here is the link for an explanation on the issue. The library itself could be found as a Maven artifact or as a Github repository. Also note that if you look at the source code (in Github repository) the package com.mgnt.lifecycle.management.backgroundrunner.example
contains complete usage example
Upvotes: 0