A. Hasemeyer
A. Hasemeyer

Reputation: 1734

How can you tell if Hangfire task was manually triggered

I have a Hangfire server set up with several recurring tasks. For local development I don't want these tasks to go through but I need to be able to manually trigger them manually through the Hangfire UI.

I am able to pull the Job Data for the currently running job but I don't see anything within it that tells me if it was manually triggered or not.

Here is an excerpt from my code where RunProcessReportsJob is my RecurringJob in Hangfire

public ExitCodeType RunProcessReportsJob(PerformContext context)
        {
                var jobId = context.BackgroundJob.Id;
                var connection = JobStorage.Current.GetConnection();
                var jobData = connection.GetJobData(jobId);

                _logger.LogInformation("Reoccurring job disabled.");
                return ExitCodeType.NoError;
        }

The jobData has a ton of information about the job and context but again I don't see anything within this that tells me if it is a manually triggered job or a scheduled job.

Upvotes: 2

Views: 2073

Answers (1)

Pieter Alberts
Pieter Alberts

Reputation: 879

Hope this helps

    private bool JobWasManuallyExecuted(string jobId)
    {
        //'Triggered using recurring job manager' -- Manually triggerd via UI
        //'Triggered by recurring job scheduler' -- using scheduller
        var jobDetails = JobStorage.Current.GetMonitoringApi().JobDetails(jobId);
        if (jobDetails == null)
            return false;

        return jobDetails.History.ToList().Any(x => x.Reason == "Triggered using recurring job manager");
    }

This message appears on the UI as well.

Executed using the scheduler: Executed using the scheduler

Manually executed Manually executed

Upvotes: 3

Related Questions