[英]How I can set timer on a single line code in java
My requirements is.. I want to set a timer on a single line code in java.我的要求是..我想在 java 的单行代码上设置一个计时器。 If time exceeded then it will throw a timeout exception and it will start to execute that single line code into a different thread.
如果超过时间,它将抛出一个超时异常,并将开始将该单行代码执行到不同的线程中。
Here is my code这是我的代码
public Object ShootSMTPMail(String subject,String body,Session session,SMTPServerInfo smtpserverInfo,InternetAddress[] mailAddress_TO) throws Exception
{
try
{
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(smtpserverInfo.SMTPUsername));
message.setRecipients(Message.RecipientType.TO, mailAddress_TO);
message.setSubject(subject);
message.setContent(body, "text/html");
Transport.send(message);// I want to set a timer on this line;
return true;
}
catch(Exception e)
{
throw e;
}
finally
{
}
}
Basically here I am sending emails through Transport.send(), and this statement taking some time to execute, So I want to throw a timeout exception to the font end and want to show the user that it will take some times to execute.基本上在这里我通过 Transport.send() 发送电子邮件,并且这个语句需要一些时间来执行,所以我想向字体端抛出一个超时异常,并希望向用户展示它需要一些时间来执行。 and meanwhile I want to execute Transport.send(message);
同时我想执行 Transport.send(message); this line in different thread and when I will receive response from Transport.send(message);
这一行在不同的线程中,我什么时候会收到来自 Transport.send(message) 的响应; this execution I will send it to font end.
这个执行我会将它发送到字体末尾。 Actually I want make this whole process asynchronous.
实际上我想让整个过程异步。 Please help me..
请帮我..
In java things like that are usually implemented as a service with internal pool of threads.在 java 中,类似的东西通常被实现为具有内部线程池的服务。
Something like that:像这样的东西:
public class EmailSenderService {
private ExecutorService threadPool = Executors.new***Pool();
public Future<?> send(Message message) {
return threadPool.submit(() -> Transport.send(message));
}
public void shutDownService() {
threadPool.shutdownNow();
...
}
}
Here Transport.send(message)
is executing asynchronously in another thread, while the Future
instance returned by send()
allows the caller to check if the task has finished, to cancel the task, etc.这里
Transport.send(message)
在另一个线程中异步执行,而send()
返回的Future
实例允许调用者检查任务是否完成,取消任务等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.