Home > Blockchain >  Running recurring job inside Startup
Running recurring job inside Startup

Time:03-04

If I have a recurring job that will be run daily inside the .net core application. For that purpose, I'm thinking to use the Hangfire library.

My question is: will placing this code for executing this daily job here in the Configure method be the most logical place or you would suggest something else?

public void Configure(IApplicationBuilder app, IBackgroundJobClient backgroundJobs, IHostingEnvironment env)
{    
    app.UseHangfireDashboard();
    backgroundJobs.Enqueue(() => Console.WriteLine("Hello world from Hangfire!"));
    ...            
}

CodePudding user response:

As your code is written it won't trigger daily, unless you restart your application on a daily basis. Also, if you you have multiple instances of your application, you will get multiple runs of your background job.

What you need to write should be something like :

RecurringJob.AddOrUpdate( "MyConsoleJobUniqueId",
                          () => Console.WriteLine("Hello world from Hangfire!"),
                          Cron.Daily );

As said by @BrandoZhang this code would be better placed in appLifetime.ApplicationStarted event handler.

CodePudding user response:

Asp.net core provide a IHostApplicationLifetime which provide the methods which could be triggered when the application host has fully started, when the application host has performed a graceful shutdown, when the application host is performing a graceful shutdown.

I think you could put this method inside the IHostApplicationLifetime's ApplicationStarted method will be good.

More details about how to use it, you could refer to this article.

  • Related