IJob defines the executable contract for a Quartz.NET scheduled job. Implement it in a C# class to place the task’s application logic in one Execute method. section 34.3.1 section 34.4
An IJob implementation separates several responsibilities:
- The job defines what to execute, such as downloading exchange rates and saving them with EF Core. section 34.3.2
- Triggers define when execution occurs, including immediate starts, intervals, start and end times, and recurring schedules. section 34.3.2
- Quartz.NET creates a new job instance and scope for each execution, allowing scoped dependencies through constructor injection. section 34.3.2
An exchange-rate job
A class such as UpdateExchangeRatesJob implements IJob and receives ILogger, ExchangeRatesClient, and AppDbContext through its constructor. Register it with AddJob<T>() using a JobKey, then attach a trigger that starts immediately and repeats every five minutes. section 34.3.2
Listing 34.11 A Quartz.NET IJob for downloading and saving exchange rates
public class UpdateExchangeRatesJob : IJob #1
{
private readonly ILogger<UpdateExchangeRatesJob> _logger; #2
private readonly ExchangeRatesClient _typedClient; #2
private readonly AppDbContext _dbContext; #2
public UpdateExchangeRatesJob( #2
ILogger<UpdateExchangeRatesJob> logger, #2
ExchangeRatesClient typedClient, #2
AppDbContext dbContext) #2
{ #2
_logger = logger; #2
_typedClient = typedClient; #2
_dbContext = dbContext; #2
} #2
public async Task Execute(IJobExecutionContext context) #3
{
_logger.LogInformation("Fetching latest rates");
var latestRates = await _typedClient.GetLatestRatesAsync(); #4
_dbContext.Add(latestRates); #5
await _dbContext.SaveChangesAsync(); #5
_logger.LogInformation("Latest rates updated");
}
}
Inspect the complete IJob implementation pattern, including constructor-injected services and the job’s execution logic. section 34.3.2
