2016-10-13 69 views
2

我正在嘗試找到一些選項來將文件的請求存儲到文件中,並且希望每小時重複一次。我每秒有大約3000個請求,我只想存儲一分鐘的請求消息,這會給我180000個請求做分析。但我想每小時對請求消息進行相同的分析。在每隔1小時的時間間隔內在文件中存儲一分鐘的Servlet請求

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
    try { 
     ServletInputStream inputStream = request.getInputStream(); 
     Reader reader = new InputStreamReader(inputStream); 
     requestMessage = gson.fromJson(reader, Request.class); 

     //I am trying to print requestMessage in one file for a minute at interval of 1 hour to do analysis on it 
     //(I am having around 3000 post requests per seconds) 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    response.setStatus(HttpServletResponse.SC_NO_CONTENT); 

} 

我曾嘗試使用下面的方法後代碼嘗試,但因爲它會啓動新的時間表,每次我有新的要求,我把相同的代碼在init()方法,但它沒有給出其輸出不能正常工作。

service = Executors.newSingleThreadScheduledExecutor(); 
service.scheduleAtFixedRate(new Runnable() { 
      @Override 
      public void run() { 
       System.out.println("Starting of 1 Hour time: "+new Date()); 
       ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); 

       exec.schedule(new Runnable(){ 
        @Override 
        public void run(){ 
         System.out.println("Starting of 1 minute: "+new Date()); 

         while(requestMessage.getID().equals("123")) 
         { 
          try { 
          System.out.println("Printing to File: "+new Date()); Files.write(Paths.get("location/requestMessage.txt"),requestMessage, StandardOpenOption.APPEND); 
          } catch (IOException e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
          } 
         } 
        } 
       }, 1, TimeUnit.MINUTES); 
      } 
     }, 0, 1, TimeUnit.HOUR); 

我有點迷失在這裏,尋找一些選擇。 這可以通過使用執行程序或線程嗎?如果沒有,我可以嘗試的其他選擇是什麼?

謝謝!

+0

這是不明確「以1小時間隔一分鐘」,你可以請你澄清? –

+0

理想情況下你可以提供一個例子來澄清? –

+0

謝謝Nicolas的回覆。我試圖更多地解釋。 – anghanravi

回答

0

如果你想在每小時1分鐘的時間內執行一個給定的任務,你所能做的最好的就是安排一個主要的任務,每一個小時將會啓動一個主要的任務,只要我們不做一個遞歸任務, t達到一分鐘。

ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); 
// Schedule the main task to be executed every one our 
service.scheduleAtFixedRate(
    new Runnable() { 
     @Override 
     public void run() { 
      // Get the initial time 
      long initial = System.currentTimeMillis(); 
      // Iterate as long as the current time - initial time is less than 60 K ms (1m) 
      do { 
       // Here is my recursive task that I want to do during 1 minute 
      } while ((System.currentTimeMillis() - initial) < 60_000L); 
     } 
    }, 0L, 1L, TimeUnit.HOURS 
); 
+0

嘿,再次感謝您的回覆。 – anghanravi

+1

我已經嘗試使用你的代碼的結構init()方法根據我的用法,它的工作。添加了Thread.sleep(5);在...做while循環。 – anghanravi

相關問題