Search code examples
c#asp.netlogginghangfire

Logging the execution of a Hangfire RecurringJob in database?


I have set up hangfire successfully for my ASP.NET project, i.e. the 11 Hangfire tables are created in my database. I tried the following command inside the Application_Start() of my project's Global.asax:

namespace myAPI
{
   public class WebApiApplication : System.Web.HttpApplication
   {
      protected void Application_Start(
      {
         System.Diagnostics.Debug.WriteLine("Recurring job will be set up.");

         RecurringJob.AddOrUpdate(
             "some-id", 
             () => System.Diagnostics.Debug.WriteLine("Job instance started at " +
                                                      DateTime.Now)),
             "*/2 * * * 1-5"); 
      }
   }
}

Sadly, inside Visual Studio's window Output > Debug I only see Reccuring job will be set up. and nothing ever after. However, a SELECT * FROM [myContext].[HangFire].[Set] shows me

Key              Score      Value     ExpireAt
recurring-jobs  1579116240  some-id   NULL

So far so good, this means that the job is indeed set up.

But how do I log inside my DB each and each time when the RecurringJob is executed? Do I assume correctly that Hangfire does not do that out of the box and I have to log it myself within the arrow-function? Or is there a more elegant way?

Question on the side: Why don't I see any output of System.Diagnostics.Debug.WriteLine within my recurring job?

References


Solution

  • The actual problem was a very trivial one, the initialization of the actual background server was missing BackgroundJobServer();. Here the fully functional code:

    namespace myAPI 
    {
      public class WebApiApplication : System.Web.HttpApplication
      {
        protected void Application_Start()
        {
           string connString = ConfigurationManager.ConnectionStrings["myContext"].ToString();
           Hangfire.GlobalConfiguration.Configuration.UseConsole();
           Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage(connString,
           new SqlServerStorageOptions {
                 CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
                 SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
                 QueuePollInterval = TimeSpan.Zero,
                 UseRecommendedIsolationLevel = true,
                 UsePageLocksOnDequeue = true,
                 DisableGlobalLocks = true
               });
            var bgndJS = new BackgroundJobServer(); // <--- this is essential!
            RecurringJob.AddOrUpdate("myRecurringJob", () => HangfireRecurringJob(), "*/2 * * * 1-5");
            System.Diagnostics.Debug.WriteLine("---> RecurringJob 'myHangfireJob' initated.");
        }
    
        public void HangfireRecurringJob() {
           System.Diagnostics.Debug.WriteLine("---> HangfireRecurringJob() executed at" + DateTime.Now);
           Console.Beep(); // <-- I was really happy to hear the beep
        }
      }
    }