ClubberLang
ClubberLang

Reputation: 1898

Delete all the Hangfire jobs

At startup, I try to delete all the existing hangfire jobs, but none of the methods I use seem to work. Notice that I use a MongoDB database, but not sure it is related to the issue.

Here is how I add my job:

RecurringJob.AddOrUpdate<IPostIndexerJob>(j => j.Execute(), configuration.GetValue<string>("Job:Interval"));

Here is my code, if anyone has an idea that help?

static private void ScheduleJobs(IConfiguration configuration)
        {
            PurgeJobs1();
            PurgeJobs2();
            PurgeJobs3();
        }

        static private void PurgeJobs1()
        {
            var mon = JobStorage.Current.GetMonitoringApi();
            mon.EnqueuedJobs("socloze-elasticsearch-post-indexer", 0, 99999999).ForEach(x =>
            {
                BackgroundJob.Delete(x.Key);
            });
        }

        static private void PurgeJobs2()
        {
            var monitor = JobStorage.Current.GetMonitoringApi();
            foreach (var queue in monitor.Queues())
            {
                PurgeQueue(queue.Name);
            }
        }

        static private void PurgeJobs3()
        {
            // Clean
            foreach (var item in Hangfire.JobStorage.Current.GetConnection().GetRecurringJobs())
                RecurringJob.RemoveIfExists(item.Id);
        }

        static private void PurgeQueue(string queueName)
        {
            var toDelete = new List<string>();
            var monitor = JobStorage.Current.GetMonitoringApi();

            var queue = monitor.Queues().First(x => x.Name == queueName);
            for (var i = 0; i < System.Math.Ceiling(queue.Length / 1000d); i++)
            {
                monitor.EnqueuedJobs(queue.Name, 1000 * i, 1000)
                    .ForEach(x => toDelete.Add(x.Key));
            }
            foreach (var jobId in toDelete)
            {
                BackgroundJob.Delete(jobId);
            }
        }

Upvotes: 1

Views: 2223

Answers (1)

MikelThief
MikelThief

Reputation: 195

To delete recurring job (what i think you meant) you should firstly ask your storage to provide you all recurring jobs you have set:

jobStorage.GetConnection().GetRecurringJobs(); // where jobStorage is your storage instance, you can access it via JobStorage.Current in static context.

then delete a desired entry:

recurringJobManager.RemoveIfExists("someId"); // where recurringJobManager is instance of IRecurringJobManager

then PurgeJobs3() should work as expected (as it uses IRecurringJobManager under the hood). Perhaps the job identifier does not match your target?

Upvotes: 0

Related Questions