Search code examples
c#.net-corescheduled-taskshangfire

Hangfire duplicates jobs on server restart


So we have an .NET Core API which uses hangfire as a task scheduler.

On startup, our API starts the following functions :

public void CreateTasks()
{
    /* DATABASE TASKS */
    SyncDatabaseTask();

    /* SMS TASKS */
    SendSmsTask();

}

public void SendSmsTask()
{
    var taskId = BackgroundJob.Schedule(() => _smsService.SendSms(), TimeSpan.FromMinutes(30));
    BackgroundJob.ContinueWith(taskId, () => SendSmsTask());
}

This creates the job SendSmsTask in Hangfire on startup and does not start a second job until the first one has been completed.

The issue that we just noticed however is that whenever our API reboots (server update for example) the existing jobs are still running and news jobs are being added.

So we would like to remove all scheduled or running jobs on startup.

I've looked through the documentation (http://docs.hangfire.io/en/latest/) but couldn't really find a solution for this issue.


Solution

  • This should solve your problem, just note that this is untested.

        private void RemoveAllHangfireJobs()
        {
            var hangfireMonitor = JobStorage.Current.GetMonitoringApi();
    
            //RecurringJobs
            JobStorage.Current.GetConnection().GetRecurringJobs().ForEach(xx => BackgroundJob.Delete(xx.Id));
    
            //ProcessingJobs
            hangfireMonitor.ProcessingJobs(0, int.MaxValue).ForEach(xx => BackgroundJob.Delete(xx.Key));
    
            //ScheduledJobs
            hangfireMonitor.ScheduledJobs(0, int.MaxValue).ForEach(xx => BackgroundJob.Delete(xx.Key));
    
            //EnqueuedJobs
            hangfireMonitor.Queues().ToList().ForEach(xx => hangfireMonitor.EnqueuedJobs(xx.Name,0, int.MaxValue).ForEach(x => BackgroundJob.Delete(x.Key)));
        }