How to maintain a job history using Quartz scheduler

后端 未结 3 641
暗喜
暗喜 2021-02-02 02:46

I\'d like to maintain a history of jobs that were scheduled by a Quartz scheduler containing the following properties: \'start time\', \'end time\', \'success\', \'error\'.

相关标签:
3条回答
  • 2021-02-02 03:05

    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, ...);
    }
    
    0 讨论(0)
  • 2021-02-02 03:05

    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);
    }
    
    0 讨论(0)
  • 2021-02-02 03:19

    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.

    0 讨论(0)
提交回复
热议问题