如何在 Quartz Enterprise Scheduler .NET 3.0 中停止调度

How to stop scheduling in Quartz Enterprise Scheduler .NET 3.0

不清楚如何在新的 Quartz Enterprise Scheduler .NET 3 中停止 scgedule。 https://www.quartz-scheduler.net/

我假设有两种方法

  1. CancelationToken
  2. await scheduler.Shutdown()

如何正确使用?

请提供代码以便澄清。

using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace GPSTransportService.Model
{
    public class DataJobScheduler
    {
        static Topshelf.Logging.NLogLogWriter logger = new Topshelf.Logging.NLogLogWriter(NLog.LogManager.GetCurrentClassLogger(), "DataJobScheduler");


        public static async Task StartAsync()
        {
            try
            {
                if (!string.IsNullOrEmpty(Properties.Settings.Default.WithCronSchedule))
                {
                    // Grab the Scheduler instance from the Factory
                    NameValueCollection props = new NameValueCollection
                    {
                        { "quartz.serializer.type", "binary" }
                    };
                    StdSchedulerFactory factory = new StdSchedulerFactory(props);
                    IScheduler scheduler = await factory.GetScheduler();

                    // and start it off
                    await scheduler.Start();

                    // define the job and tie it to our HelloJob class
                    IJobDetail job = JobBuilder.Create<DataJob>().WithIdentity("dataJob", "groupMain").Build();

                    // Trigger the job to run now, and then repeat every 10 seconds
                    ITrigger trigger = TriggerBuilder.Create().WithIdentity("triggerMain", "groupMain").StartNow().WithCronSchedule(Properties.Settings.Default.WithCronSchedule).Build();

                    // Tell quartz to schedule the job using our trigger
                    await scheduler.ScheduleJob(job, trigger);

                    // some sleep to show what's happening
                    await Task.Delay(TimeSpan.FromSeconds(10));

                }
                else
                {
                    logger.Error("WithCronSchedule is not defined. Check app.config using definition in http://www.quartz-scheduler.net/documentation/quartz-2.x/tutorial/crontriggers.html");
                }
            }
            catch (SchedulerException ex)
            {
                logger.Error(ex);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }


        public async Task<bool> StopAsync()
        {
            try
            {
                // Grab the Scheduler instance from the Factory
               /* NameValueCollection props = new NameValueCollection
                    {
                        { "quartz.serializer.type", "binary" }
                    };
                StdSchedulerFactory factory = new StdSchedulerFactory(props);
                IScheduler scheduler = await factory.GetScheduler();

                // and last shut down the scheduler when you are ready to close your program 
                await scheduler.Shutdown();*/


            }
            catch (Exception)
            {

                throw;
            }

            return true;
        }
    }
}

我在这个例子中使用了 Simple Injector,这是我对容器的设置:

var container = new Container();
container.Options.DefaultLifestyle = new WebRequestLifestyle();

container.RegisterSingleton<Scheduler>();
container.Register<ISchedulerFactory>(() => new StdSchedulerFactory(), Lifestyle.Singleton);

container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.Verify();

DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));

单例class:

public class Scheduler
{
    private readonly ISchedulerFactory _factory;

    private static Scheduler _instance;

    public static Scheduler Instance => _instance;

    public Task<IScheduler> Current => _factory.GetScheduler();

    public Scheduler(ISchedulerFactory factory)
    {
        _factory = factory;
        if (_instance == null)
        {
            _instance = this;
        }
    }
}

启动调度程序:

// get a scheduler, start the schedular before triggers or anything else
var sched = await Scheduler.Instance.Current;
await sched.Start();

// create job
var job = JobBuilder.Create<SimpleJob>()
      .WithIdentity("job1", "group1")
      .Build();

// create trigger
var trigger = TriggerBuilder.Create()
       .WithIdentity("trigger1", "group1")
       .WithSimpleSchedule(x => x.WithIntervalInSeconds(1).RepeatForever())
       .Build();

// Schedule the job using the job and trigger 
await sched.ScheduleJob(job, trigger);

正在停止调度程序:

var sched = await Scheduler.Instance.Current;
await sched.Shutdown();

或者你可以只注入 ISchedulerFactory 并使用:var sched = await _factory.GetScheduler(); 而不是 var sched = await Scheduler.Instance.Current;

我已经在 github 上创建了示例项目,您可以随意对其进行测试。希望这有帮助。