Contents
data/authors/Paul Logan.json

Disabling Hangfire jobs when in development

Contents

Hangfire - hang fire 🛑

My previous technique for preventing Hangfire scheduled jobs from firing when I was debugging the app is shown below. One major drawback though, is that the jobs do not show up on the Hangfire Dashboard for inspecting.

using Hangfire;
using System.Configuration;
using System.Linq;

namespace MyApp
{
    public static class ScheduledJobs
    {

        public static void Initialise()
        {
            if (ConfigurationManager.AppSettings["IsDeveloperMode"] == "true") return;
            RecurringJob.AddOrUpdate("MyApp.ScheduledJob1", () => new RecalculateFigures().UpdateAll(10, false), "*/5 * * * 1-6");
            RecurringJob.AddOrUpdate("MyApp.ScheduledJob2", () => new SendWeeklyReports().UpdateAll(0, true), "15 06 * * 1-5");
            RecurringJob.AddOrUpdate("MyApp.ScheduledJob3", () => new CheckForUpdates(), "0 * * * *");
		}
    }
}

My new and improved technique creates the scheduled jobs so that I can view them on the Dashboard. This allows me to tick a job on the Dashboard and run it manually when necessary.

using Hangfire;
using System.Configuration;
using System.Linq;

namespace MyApp
{
    public static class ScheduledJobs
    {

        public static void Initialise()
        {
            RecurringJob.AddOrUpdate("MyApp.ScheduledJob1", () => new RecalculateFigures().UpdateAll(10, false), SetSchedule("*/5 * * * 1-6"));
            RecurringJob.AddOrUpdate("MyApp.ScheduledJob2", () => new SendWeeklyReports().UpdateAll(0, true), SetSchedule("15 06 * * 1-5"));
            RecurringJob.AddOrUpdate("MyApp.ScheduledJob3", () => new CheckForUpdates(), SetSchedule("0 * * * *"));
        }

        private static string SetSchedule(string cronExpression) => ConfigurationManager.AppSettings["IsDeveloperMode"] == "true" ? Cron.Never() : cronExpression;
    }
}