How to maintain a job history using Quartz scheduler

喜你入骨 提交于 2019-12-02 19:42:20

The way to do this is to generate an identifier in JobToBeExecuted, store it in the JobExecutionContext and retrieve it again from the JobExecutionContext in JobWasExecuted.

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, ...);
}

The scheduler has to maintain a key that lets it correlate each history entry. There must be a unique job ID of some kind that's created when a job kicks off to be able to accomplish this.

You don't mention such a thing, so I thought it was worth a suggestion.

UPDATE: I'd INSERT a record into the database when a job is created and get back the primary key (maybe a GUID). I'd use that as the key.

If you're happy to just update the database at the end, you can get the job name and run time from the 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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!