0
votes

So I'm trying to have my application send a string to a text file every minute, So in my Global.asax.cs file I have this setup:

public class Startup
{

    public void Configuration(IAppBuilder app)
    {
        GlobalConfiguration.Configuration

            .UseSqlServerStorage("AppContext");

        app.UseHangfireDashboard();

        app.UseHangfireServer();

    }
}

public class HeartbeatSetup
{
    public static void Heartbeat()
    {
        var config = new NLog.Config.LoggingConfiguration();

        var logFile = new NLog.Targets.FileTarget() { FileName = "heartbeat.txt", Name = "logfile" };

        config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Trace, logFile));

        NLog.LogManager.Configuration = config;

        var logger = NLog.LogManager.GetCurrentClassLogger();

        var currentTime = DateTime.Now.ToString();

        RecurringJob.AddOrUpdate("heartbeat", () => logger.Trace("Test"), Cron.Minutely);
    }
}

So this create the job ok and runs every minute, but the job does not complete and throws the following error:

No parameterless constructor defined for this object

Does anyone have a solution to this or an alternative method of doing this?

1
Alternative is to use proper pub-sub instead of the Hangfire. However if the Hangfire is the only option for you then you can try wrapping stuff for your call (with creating and configuring logger) as public static method without any parameters. Also take a look at how Hangfire stores registered delegates at SqlServer tables. This might give you a clue about what is a runnable Hangfire call target - Chizh

1 Answers

1
votes

So I fixed this by referencing another static method created below:

public class HeartbeatSetup
{
    public static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
    public static void Heartbeat()
    {
        try
        {
            RecurringJob.AddOrUpdate("heartbeat", () => Fire(), Cron.Minutely);
        }
        catch (Exception ex)
        {
            logger.Fatal(ex, "error");
            throw;
        }
    }

    public static void Fire()
    {
        var config = new NLog.Config.LoggingConfiguration();

        var logFile = new NLog.Targets.FileTarget("logfile") { FileName = "heartbeat.txt" };

        config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, logFile);

        NLog.LogManager.Configuration = config;

        var currentTime = DateTime.Now.ToString();

        try
        {
            logger.Info(currentTime + " - beep");
        }
        catch (Exception ex)
        {
            logger.Fatal(ex + " - beeeeeeeeeeeeeeeeeeeeeeeeeeeeeep");
        }

    }
}