如何为Java中的公共方法超时



我已经搜索了一段时间,但我没有找到一个具体的独特的解决方案,这个问题,一些使用函数方法,如。settimeout(…)左右,但我只是想设置超时在我的项目中的一个公共方法。为什么?因为在我下面展示的代码中有时我在发布wordpress帖子的网站上找不到答案它会杀死所有预定的发布处理程序

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);
}

如何使整个blogPublish函数超时?我需要跳过它,如果5秒后,我仍然没有从我的网站发布完成的回复,因为它太慢了,或者在那一刻无法访问。

看看Guava的SimpleTimeLimiter.callWithTimeout

在你的例子中,它可能看起来像这样:

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); 

最新更新