每5秒后Java轮询5次

时间:2016-10-26 08:21:23

标签: java arrays timer polling

单击下载按钮从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 
            } 
        }        
    }


}

3 个答案:

答案 0 :(得分:1)

你需要的是某种计时器。以下是有关如何使用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您希望{1}} schedule首次执行1秒(downloadTask),然后每5秒执行一次1000 milliseconds 5000 milliseconds 1}})。

然而,除非您在成功下载或任务执行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
};

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

答案 1 :(得分: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;
                    }
                 } 

答案 2 :(得分:0)

您也可以使用awaitility来完成此操作。请查看this link如何使用