【问题标题】:How to timeout for a Public method in Java?Java中的公共方法如何超时?
【发布时间】:2023-03-10 01:58:02
【问题描述】:

我已经搜索了一段时间,但我没有找到解决这个问题的具体独特解决方案,有些使用函数方法,如 .setTimeout(...) 左右,但我只想将超时设置为 public我项目中的方法。 为什么?因为在我向您展示的代码中,有时我在发布 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 秒后我仍然没有从我的网站上收到已完成发布的回复,我需要跳过它,因为它太慢或在那一刻无法访问。

【问题讨论】:

    标签: java function methods timeout settimeout


    【解决方案1】:

    看看来自 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); 
    

    【讨论】:

    • 这似乎是一个很好的解决方案,但我有点新手,我不知道如何实现它,我什至搜索过但没有示例,只有代码文档。你有一个如何在我的案例中构建它的例子吗?我已经在我之前粘贴的函数的类中导入了库。
    • 你需要将你的函数包装成一个Callable,这样它才能被SimpleTimeLimiter接受。我已经编辑了我的答案以提供一个例子。附:方法参数过多(在您的情况下为 6 个)是代码异味。
    猜你喜欢
    • 2011-04-11
    • 2015-03-07
    • 2011-01-30
    • 1970-01-01
    • 2011-04-19
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    相关资源
    最近更新 更多