Why is hangfire not printing out the message in my method

460 views Asked by At

I have written a simple console app that should print a message every minute. I do get the first print message saying "starting" however i do not get the message in the PrintTest()

method in my console. What is the reason for this ? By the way, this is a .net core console application.

class Program
{
    static void Main(string[] args) 
    {
        Console.WriteLine("Starting");
        GlobalConfiguration
            .Configuration
            .UseSqlServerStorage(@"Server=127.0.0.1,1433; Database=HFTest; User Id=sa; Password=Password123");

        RecurringJob.AddOrUpdate((() => PrintTest()), Cron.Minutely());
        Console.ReadKey();
    }

    public static void PrintTest()
    {
        Console.WriteLine("Hangfire Server started. Press any key to exit...");
    }
}
1

There are 1 answers

0
Ryan On

You need to create a BackgroundJobServer with using block and put your RecurringJob in it:

static void Main(string[] args)
    {
        Console.WriteLine("Starting");
        GlobalConfiguration
            .Configuration
            .UseColouredConsoleLogProvider()
            .UseSqlServerStorage(@"Server=127.0.0.1,1433; Database=HFTest; User Id=sa; Password=Password123");

        using (var server = new BackgroundJobServer())
        {
            RecurringJob.AddOrUpdate(() => PrintTest(), Cron.Minutely());
            Console.ReadKey();
        }

    }

Refer to https://docs.hangfire.io/en/latest/background-processing/processing-jobs-in-console-app.html