We have many solutions that uses Recurring Tasks to send out some daily emails, and we have issues making sure the website is running at the scheduled times.
Its not that important that the emails are being sent at that exact momemt specificed, so we’re missing a feature when adding Recurring Jobs to tell HangFire that its okay to run them at system startup if the time it should have been run was missed. So far we added this feature like this which we run in our Owin Statup Handler.
using (var connection = JobStorage.Current.GetConnection())
{
var recurringJobs = connection.GetRecurringJobs();
foreach (var job in recurringJobs)
{
var cronSchedule = NCrontab.CrontabSchedule.Parse(job.Cron);
var nextExecuting = DateTime.MinValue;
var lastExecution = job.LastExecution;
if (lastExecution.HasValue)
{
nextExecuting = cronSchedule.GetNextOccurrence(lastExecution.Value);
}
if (nextExecuting < job.NextExecution)
{
var executingDate = DateTime.UtcNow;
var state = new EnqueuedState {Reason = "Triggered by startup"};
var client = new BackgroundJobClient();
var jobId = client.Create(job.Job, state);
connection.SetRangeInHash(
String.Format("recurring-job:{0}", job.Id),
new Dictionary<string, string>
{
{"LastExecution", JobHelper.SerializeDateTime(executingDate)},
{"LastJobId", jobId},
});
}
}
}