2010-06-02 81 views
9

我想保留Quartz調度程序調度的作業歷史記錄,其中包含以下屬性:'開始時間','結束時間','成功','錯誤」。如何使用Quartz調度程序來維護作業歷史記錄

有兩個接口可用於此:ITriggerListenerIJobListener(我正在使用C#接口的命名約定,因爲我使用的是Quartz.NET,但可能會要求提供Java版本的相同問題)。

IJobListener有一個JobToBeExecuted和一個JobWasExecuted方法。後者提供JobExecutionException,以便您知道何時出現問題。但是,無法關聯JobToBeExecutedJobWasExecuted。假設我的工作運行了十分鐘。我從t0t0+2開始(因此它們重疊)。我收到兩個電話JobToBeExecuted,並將兩個開始時間插入我的歷史記錄表中。當這兩項工作完成t1t1+2我得到兩個電話JobWasExecuted。我如何知道每次調用中要更新的數據庫記錄(用相應的開始時間存儲結束時間)?

ITriggerListener還有另一個問題。當作業失敗時,無法在TriggerComplete方法中發現任何錯誤。

我該如何獲得理想的行爲?

回答

12

做到這一點的方法是在JobToBeExecuted生成一個標識符,它存儲在JobExecutionContextJobExecutionContextJobWasExecuted再次找回它。

public void JobToBeExecuted(JobExecutionContext context) 
{ 
    // Insert history record and retrieve primary key of inserted record. 
    long historyId = InsertHistoryRecord(...); 
    context.Put("HistoryIdKey", historyId); 
} 

public void JobWasExecuted(JobExecutionContext context, 
          JobExecutionException jobException) 
{ 
    // Retrieve history id from context and update history record. 
    long historyId = (long) context.Get("HistoryIdKey"); 
    UpdateHistoryRecord(historyId, ...); 
} 
4

調度程序必須保持一個關鍵字,使其關聯每個歷史記錄條目。必須有一個獨特的工作編號,這是在工作開始時才能完成的。

你不提這樣的事情,所以我認爲這是值得一提的建議。

更新:當創建一個作業時,我會向數據庫中插入一條記錄並取回主鍵(也許是一個GUID)。我會用它作爲關鍵。

+0

你有什麼想法,我能找到這樣關鍵? – 2010-06-02 13:49:23

+0

當前的關鍵是JobGroup,JobName和日期和時間。看來2.0版本中會出現更好的關鍵。 – 2011-07-15 12:44:04

1

如果你很高興只更新末尾的數據庫,你可以得到任務名稱,從IJobExecutionContext運行時間:

public void JobWasExecuted(JobExecutionContext context, 
         JobExecutionException jobException) 
{ 
    var sql = @"INSERT INTO MyJobAuditHistory 
       (JobKey, RunTime, Status, Exception) VALUES (?, ?, ?, ?)"; 

    // create command etc. 
    command.Parameters.Add(context.JobDetail.Key.ToString()); 
    command.Parameters.Add(context.JobRunTime); 
    command.Parameters.Add(jobException == null ? "Success" : "Fail"); 
    command.Parameters.Add(jobException == null ? null : jobException.Message); 
}