2012-12-12 33 views
0

我目前有一個web服務,它存儲了某些值的關鍵映射,我設法創建了一個由web服務接收的命令的後臺日誌記錄系統。現在我必須實現一個將日誌存儲到文件中的檢查指針,我已經將它作爲Timer Task的擴展來實現。所以我想我可能會使用計時器來安排檢查指針每20分鐘左右執行一次任務。我的問題是,除了調用檢查指針之外,我還要測試是否還有任何對服務的調用正在處理中,請等待它完成,然後阻止webservice直到我發送一個resume命令,一個quiesce方法。java中的日誌檢查指針

public class MyCheckpointer extends TimerTask implements Checkpointer { 

ObjectOutputStream out; 
FileOutputStream file; 
MyLogger log; 

public MyCheckpointer(MyLogger l) 
{ 
    File log_txt = new File("./log.txt"); 
    try { 
     this.file = new FileOutputStream(log_txt); 
     this.out = new ObjectOutputStream(this.file); 

    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    this.log = l; 

} 

@Override 
public void run() { 
    // TODO Auto-generated method stub 
    this.writeLog(); 
} 

private void writeLog() 
{ 
    ArrayList<LogRecord> l = this.log.getArray(); 
    Iterator<LogRecord> e = l.iterator(); 
    do 
    { 
     try { 
      out.writeObject(e.next()); 
     } catch (IOException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 

    }while(e.hasNext()); 
} 

} 

回答

0

Web服務實現和MyCheckpointer類可以共享同步對象。例如java.util.concurrent.lock中:

Lock lock = new ReentrantLock(); 

然後他們兩個應該叫:

lock.lock(); 
service the command and log/write logs to file 
lock.unlock(); 
0

我不知道它是否適合全你的使用情況,但我會用一個日誌框架,支持asynchrous記錄,而不是滾動您自己的意見。例如,log4j提供了一個異步appender:http://www.slf4j.org/nlog4j/api/org/apache/log4j/AsyncAppender.html

+0

對不起......我忘了說,這是一個作業完成的,所以我需要用手執行每個部分。 – redspider