Reputation:
I've searched for a while but I didn't found a concrete unique solution for this problem, some use function methods like .setTimeout(...) or so, but I just want to set timeout to one of public methods in my project. Why? Because in the code I'm showing you bottom sometimes I have no answer from my website where I'm posting my wordpress post and it kill all the scheduled posting handler.
public void blogPublish(String articleTitle, String articleText, Date pubDate, String sourceDomain, String sourceAuthor, String blogCategory) throws XmlRpcFault{
String fullArticleContent = articleText;
XmlRpcArray categoryArray = new XmlRpcArray();
categoryArray.add(blogCategory);
this.post = new Page();
this.post.setTitle(articleTitle);
this.post.setDescription(fullArticleContent);
this.post.setDateCreated(pubDate);
this.post.setCategories(categoryArray);
String newPostIds = this.WP.newPost(post, true);
int newPostId = Integer.valueOf(newPostIds).intValue();
Page postNow = WP.getPost(newPostId);
System.out.println("Article Posted. Title=> "+ articleTitle);
}
How can I timeout the whole blogPublish function? I need to skip it if after 5 seconds I still have no reply of done publishing from my website because it's too slow or not reachable in that moment.
Upvotes: 3
Views: 1187
Reputation: 26703
Have a look at SimpleTimeLimiter.callWithTimeout
from Guava.
In your case it could look like similar to this:
final String articleTitle = ...;
final String articleText = ...;
final Date pubDate = ...;
final String sourceDomain = ...;
final String sourceAuthor = ...;
final String blogCategory = ...;
final SomeClassOfYours someClassOfYours = ...;
Callable<Void> callable = new Callable<Void>() {
public Void call() throws XmlRpcFault {
someClassOfYours.blogPublish(articleTitle, articleText, pubDate, sourceDomain, sourceAuthor, blogCategory);
}
}
new SimpleTimeLimiter().callWithTimeout(callable, 5, TimeUnit.SECONDS, true);
Upvotes: 4