Search code examples
c#.net-corehangfire

How to debug hangfire jobs locally while not triggering scheduled jobs


Is there a way to run Hangfire Jobs locally while debugging in Visual Studio while not triggereing any scheduled jobs defined in the database.

For example, I have HangfireJobA and I want to run it one time while in Visual Studio and step through it, however, when debugging, if HangfireJobA is configured in the DB to run every 3 minutes, I don't necessary want that schedule to be triggered.

How can I logically separate the two requirements. I don't want the scheduled jobs to run while I am debugging.

Currently, I have created a #IF(DEBUG) ...#endif and dynamically load all classes that implement an IServiceWorker interface and then select one to instantiate and run it's worker function. This seems hacky and there may be a better way. Any suggestions?


Solution

  • The solution being test driven at the moment is:

    1. Require all Developers install SQL Server LocalDB

    2. In appsettings.local.json add the local version of the hangfire db.

      "HangfireDB": "Data Source = localhost; Initial Catalog = Hangfire_XXXX; Integrated Security = SSPI;"

    3. In registration, there is a differentiation between debugging locally or running in a target environment.

    NOTE : Adding Cron.Never() as the Schedule will place the job in a visible but disabled state. This means the only way to trigger a job is to implicitly click the "Trigger Now", thus invoking the debugger on it.

    public static class RegisterServiceWorkers
    {
        public static void Register(string environment)
        {
            if (environment.Equals("LOCAL"))
            {
                    
                RecurringJob.AddOrUpdate<LeaseReportDataBuildupWorker>("LeaseReportDataBuildupWorker_LIFO", x => x.PerformServiceWork("LIFO"), () => Cron.Never());
                RecurringJob.AddOrUpdate<LeaseReportDataBuildupWorker>("LeaseReportDataBuildupWorker_FIFO", x => x.PerformServiceWork("FIFO"), () => Cron.Never());
                RecurringJob.AddOrUpdate<LeaseReportDataBuildupWorker>("LeaseReportDataBuildupWorker_RANDOM", x => x.PerformServiceWork("RANDOM"), () => Cron.Never());
            }
            else
            {
                RecurringJob.AddOrUpdate<LeaseReportDataBuildupWorker>("LeaseReportDataBuildupWorker_FIFO", x => x.PerformServiceWork("LIFO"), () => "*/3 * * * *");
                RecurringJob.AddOrUpdate<LeaseReportDataBuildupWorker>("LeaseReportDataBuildupWorker_LIFO", x => x.PerformServiceWork("FIFO"), () => "*/3 * * * *");
                RecurringJob.AddOrUpdate<LeaseReportDataBuildupWorker>("LeaseReportDataBuildupWorker_RANDOM", x => x.PerformServiceWork("RANDOM"), () => "*/3 * * * *");
            }
    
    
        }
    }