hi I have hangfire up and running in startup.cs and dashboard is running but i want to add a job to add field to sqlserver database every minute.can U help me?
I have implemented a service class to store data to db. which will be used to recurring job
public interface ITestService{
Task SaveData();
}
public class TestService : ITestService{
private readonly ApplicationDbContext _dbContext;
public TestService(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task SaveData()
{
_dbContext.Users.Add(new User
{
UserName = "testUser",
Email = "testa@gmail.com"
});
await _dbContext.SaveChangesAsync();
}
}
Inside ConfigureServices()
in startup.cs I have registered hangfire with the dbcontext and serviceClass which will be saving data to the database
services.AddHangfire(x => x.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection")));
services.AddHangfireServer();
services.AddTransient<ApplicationDbContext>(); //Your DbContext
services.AddTransient<ITestService, TestService>(); //Your Service to store data
in the same file change the configure
method to,
Configure(IApplicationBuilder app, IHostingEnvironment env, IRecurringJobManager recurringJobManager, ITestService testService)
inside the above method add the call the following methods
app.UseHangfireDashboard();
recurringJobManager.AddOrUpdate("First recurring job", () => testService.SaveData(), Cron.MinuteInterval(1)); //Instead of the Cron.MinuteInterval() you can use cron expressions