2016-10-13 15 views
2

1分間の投稿要求をファイルに保存するオプションを見つけようとしていて、1時間ごとに同じリクエストを繰り返す必要があります。私は毎秒約3000件のリクエストを受けていますが、私は180000分のリクエストを解析するために1分のリクエストメッセージを保存したいだけです。しかし、私は毎時間要求メッセージについて同じ分析をしたいと思っています。1時間間隔ごとにファイルの1分間のサーブレット投稿要求を保存する

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

} 

私は、POSTメソッドのコードの下に使用してみましたが、それは新しいスケジュール毎回を開始しますので、それが正常に動作しない、私は新しい要求があると私は、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); 

私はここでいくつかのオプションを探しています。 ExecutorsまたはThreadを使用するとこれが可能ですか?そうでない場合は、私が試すことができる他の選択肢は何ですか?

ありがとうございました!

+0

これは「1分間隔で1分」はわかりませんが、明確にしてください。 –

+0

理想的には明確にするための例を挙げることができますか? –

+0

Nicolasに返信いただきありがとうございます。私はもう少し詳しく説明しようとしました。 – anghanravi

答えて

0

毎時1分の間に特定のタスクを実行したい場合は、1時間ごとに起動されるメインタスクをスケジュールし、再帰的なタスクを実行し続ける限り、 1分に達する。

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); in ... whileループ。 – anghanravi

関連する問題