Skip to main content

Use exception handling

When working with scheduled jobs, it is essential to handle exceptions that may occur during the job's execution. Rather than allowing exceptions to propagate and potentially interrupt the job, it is better to catch them and handle them gracefully.

One approach to handling exceptions in scheduled jobs is to log the error messages, rather than throwing the exception. By doing so, the job can continue to execute without interruption.

In addition to error logging, developers should also implement alerting mechanisms that enable them to monitor the scheduled job's health and performance. One way to achieve this is by storing log messages in a centralized repository, such as Elasticsearch, monitoring them using a visualization tool, such as Grafana, and set up alerts for specific conditions or events

public class ExpiredAlarmCleanerJob : IJob
{
private readonly IEnumerable<IAlarmKeeperService> _alarmKeeperServices;
private readonly ILogger<ExpiredAlarmCleanerJob> _logger;

public ExpiredAlarmCleanerJob(
IEnumerable<IAlarmKeeperService> alarmKeeperServices,
ILogger<ExpiredAlarmCleanerJob> logger)
{
_alarmKeeperServices = alarmKeeperServices;
_logger = logger;
}

public async Task Execute(IJobExecutionContext context)
{
try
{
_logger.LogInformation(LoggingEvents.StartExpiredCleanerJob, "ExpiredAlarmCleanerJob Service started");

await RemoveExpiredAlarms();

_logger.LogInformation(LoggingEvents.StopExpiredCleanerJob, "ExpiredAlarmCleanerJob Service stopped");
}
catch (Exception e)
{
_logger.LogError(LoggingEvents.ExpiredCleanerJobFailed, e, e.Message);
}
}

private async Task RemoveExpiredAlarms()
{
NewRelic.Api.Agent.NewRelic.SetTransactionName("Jobs", "RemoveExpiredAlarms");

foreach (IAlarmKeeperService alarmKeeperService in _alarmKeeperServices)
{
await alarmKeeperService.RemoveExpiredAlarms();
}
}
}