如何在C#中使用JobStorage获取所有Hangfire作业列表?

时间:2019-01-11 06:44:54

标签: c# asp.net-mvc asp.net-core-2.0 hangfire hangfire-autofac

我正在使用Hangfire BackgroundJob使用以下代码在C#中创建后台作业。

var options = new BackgroundJobServerOptions
        {
            ServerName = "Test Server",
            SchedulePollingInterval = TimeSpan.FromSeconds(30),
            Queues = new[] { "critical", "default", "low" },
            Activator = new AutofacJobActivator(container),
        };
        var jobStorage = new MongoStorage("mongodb://localhost:*****", "TestDB", new MongoStorageOptions()
        {
            QueuePollInterval = TimeSpan.FromSeconds(30)                
        });
        var _Server = new BackgroundJobServer(options, jobStorage);

它将创建Jobserver对象,此后,我将创建时间表,定期任务,如下所示。

var InitJob = BackgroundJob.Schedule<TestInitializationJob>(job => job.Execute(), TimeSpan.FromSeconds(5));
        var secondJob = BackgroundJob.ContinueWith<Test_SecondJob>(InitJob, job => job.Execute());
        BackgroundJob.ContinueWith<Third_Job>(secondJob, job => job.Execute());
        RecurringJob.AddOrUpdate<RecurringJobInit>("test-recurring-job", job => job.Execute(), Cron.MinuteInterval(1));

此后,我想在我的应用程序停止或关闭时删除或停止所有作业。因此,在我的应用程序的OnStop事件中,我编写了以下代码。

var monitoringApi = JobStorage.Current.GetMonitoringApi();
                    var queues = monitoringApi.Queues();// BUT this is not returning all queues and all jobs
                    foreach (QueueWithTopEnqueuedJobsDto queue in queues)
                    {
                        var jobList  = monitoringApi.EnqueuedJobs(queue.Name, 0, 100);
                        foreach (var item in jobList)
                        {
                            BackgroundJob.Delete(item.Key);
                        }
                    }

但是,上面的代码无法获得所有作业和所有队列。它总是返回"default"队列,而不返回所有作业。

有人可以使用Hangfire JobStorage获取所有作业,并在应用程序停止时停止这些作业吗?

任何帮助将不胜感激!

谢谢

0 个答案:

没有答案