Java 每 5 秒轮询 5 次

问题描述 投票:0回答:4

单击下载按钮将从 SAN 位置获取 PDF。但有时由于 XYZ 原因,文档在 SAN 不可用。我需要实现一个轮询机制,以便单击下载后每 5 秒在 SAN 位置搜索文档 5 次,并返回迭代号。搜索成功后会在日志中显示。

package abc.documentdownload;

import abc.util.Email;

import java.io.BufferedOutputStream;
import java.io.IOException;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DownloadDocServlet extends HttpServlet {
    private static final Log log = LogFactory.getLog(DownloadDocServlet.class);
    private static final String CONTENT_TYPE = "text/html; charset=windows-1252";

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws ServletException,
                                                           IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request,
                       HttpServletResponse response) throws ServletException,
                                                            IOException {
        response.setContentType(CONTENT_TYPE);
        DownloadDocDAO DownloadInstance = new DownloadDocDAO();
        String downloadType = request.getParameter("downloadType");
        String pNumber = request.getParameter("PNumber");
        BufferedOutputStream output = null;
        String strFileName = pNumber + ".pdf";
        if(downloadType != null && downloadType.equalsIgnoreCase("download")){
            try{
                byte[] content=DownloadInstance.getP(pNumber);                
                log.info("COnverting content into PDF in EmailServlet");
                System.out.println("COnverting content into PDF in EmailServlet");
                response.setContentType("application/pdf");
                response.setHeader("Content-Disposition","attachment; filename=\"" + strFileName + "\"");
                response.setHeader("Cache-Control","no-cache"); 
                response.setHeader("Cache-Control","no-store"); 
                response.setHeader("Pragma","no-cache");
                response.setDateHeader("Expires", 0);
                output = new BufferedOutputStream(response.getOutputStream());
                output.write(content);
                output.flush();                            
                output.close();                

            }
            catch (Exception ex) {
                ex.printStackTrace();
                log.error("Error in DownloadDocServlet ", ex);
                /* Using the below block to trigger the email whenever there is a error*/
                Writer result = new StringWriter();
                PrintWriter printWriter = new PrintWriter(result);
                ex.printStackTrace(printWriter);
                Email emailSend = new Email();                                  
                int strEmailConfirm = emailSend.sendEmail("Exception in DownloadDocServlet of documentdownload package for pno :"+pNumber,"<B>Please find Exception Details for the DownloadDocServlet of documentdownload package</b><br><br>"+result.toString());
                log.info("strEmailConfirm in DownloadDocServlet"+strEmailConfirm); // if value is 1 ,  mail will be trigger is successful 
            } 
        }        
    }


}
java arrays timer polling
4个回答
3
投票

你需要的是某种计时器。以下是如何使用

TimerTasks
的示例。

首先

Timer

Timer downloadTimer = new Timer();

在您安排

TimerTask
之前,它不会执行任何操作:

TimerTask downloadTask = new TimerTask() {
    @Override
    public void run() {
       //try to download here
    };
}

现在您需要安排任务:

downloadTimer.schedule(downloadTask,1000,5000); 

这告诉您的

downloadTimer
您想要
schedule
downloadTask
在 1 秒内第一次执行 (
1000 milliseconds
),然后每 5 秒执行一次 (
5000 milliseconds
)。

但是它会持续运行,除非您下载成功或任务执行了 5 次后停止任务:

private int count;
public void run() {
   if(count++==5){
       downloadTimer.cancel();  // will stop the timer
       downloadTimer.purge();   // will remove all canceled tasks from the timer
       return;   // makes sure the task will not be executed to the end
   }
   // try to download here
   // if download successful cancel and purge as well
};

这应该可以解决问题,但我不能说这是否是解决您问题的最佳解决方案。


0
投票

线程睡眠对我来说效果很好

 for(int i=0;i<5;i++)
                 {
                     content=getPDAO.getPFromEb( strPN);
                      DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
                      Date dateobj = new Date();
                    if(content==null) 

                     {  
                        Thread.sleep(5000);
                        }
                    else {
                        content=getPDAO.getPFromEb( strPN);
                        break;
                    }
                 } 

0
投票

您还可以使用

awaitility
来完成此操作。请查看此链接了解如何使用


0
投票

可以使用 Spring RetryTemplate 来实现。 就我而言,我实现了下载文件并在文件仍未生成时抛出异常的方法

private Response downloadPDF(String documentId) {
    Response downloadResponse = apiClient.downloadFile(documentId);
    if (downloadResponse.status() == HttpStatus.SC_NOT_FOUND) {
      String message = String.format("Document with id %s not found", documentId);
      log.warn(message);
      throw new NoSuchElementException(message);
    }
    return downloadResponse;
  }

然后我有异常重试的方法

private Response downloadPDFWithRetry(String documentId) {
    return downloadRetryTemplate.execute(context -> downloadPDF(documentId));
  }

并重试模板初始化

@Bean("downloadRetryTemplate")
  public RetryTemplate downloadRetryTemplate() {
    return RetryTemplate.builder()
        .maxAttempts(downloadMaxAttempts)
        .fixedBackoff(downloadBackoff)
        .traversingCauses()
        .retryOn(List.of(Exception.class))
        .build();
  }
© www.soinside.com 2019 - 2024. All rights reserved.