Windows服务结束后,Quartz.net的工作似乎仍然存在

时间:2016-03-04 02:57:51

标签: c# .net windows-services quartz-scheduler quartz.net

我是Quartz.net的新手,现在只是感受一下。我正在设置Quartz.net作业以从我的Windows服务运行。

我的Windows服务有两种启动模式a)如果项目作为Windows服务运行,它将作为普通服务运行。 b)如果项目是从Visual Studio中以调试模式运行的,它将以交互模式运行(这样我就可以根据上下文将调试信息输出到控制台与记录器)。它在Main()(仅摘录)中执行如下操作:

if (Environment.UserInteractive && System.Diagnostics.Debugger.IsAttached) {
    System.Reflection.MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
    onStartMethod.Invoke(myService, new object[] { new string[] { } });
    Console.WriteLine("Service started.");
    Console.WriteLine("Press a key to stop service and finish process...");
    Console.ReadKey();
    System.Reflection.MethodInfo onStopMethod = typeof(ServiceBase).GetMethod("OnStop", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
    onStopMethod.Invoke(myService, null);
    Console.WriteLine("Service stopped.");
} else {
    ServiceBase.Run(myService);
}

现在在MyService中我有以下工作,这个工作似乎按预期正确运行:

protected override void OnStart(string[] args)
{
    _schedulerFactory = new StdSchedulerFactory();
    IScheduler scheduler = _schedulerFactory.GetScheduler();
    scheduler.Start();

    IJobDetail syncJob = JobBuilder.Create<MySyncJob>()
            .WithIdentity("syncJob")
            .Build();

    ITrigger trigger = TriggerBuilder.Create()
        .StartAt(new DateTimeOffset(DateTime.UtcNow.AddSeconds(5)))
        .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever())
        .Build();

    scheduler.ScheduleJob(syncJob, trigger);

}

然而,当我从我的Visual Studio以调试模式运行我的项目时,当我停止服务时,控制台说“Service stopped”,但是Quartz.net syncJob似乎继续运行(控制台输出继续)为什么会这样是

1 个答案:

答案 0 :(得分:5)

您需要更新OnStop方法,以便在服务停止时关闭调度程序。

private ISchedulerFactory _schedulerFactory;
private IScheduler _scheduler;

protected override void OnStart(string[] args)
{
    _schedulerFactory = new StdSchedulerFactory();
    _scheduler = _schedulerFactory.GetScheduler();
    _scheduler.Start();

    IJobDetail syncJob = JobBuilder.Create<MySyncJob>()
        .WithIdentity("syncJob")
        .Build();

    ITrigger trigger = TriggerBuilder.Create()
        .StartAt(new DateTimeOffset(DateTime.UtcNow.AddSeconds(5)))
        .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever())
        .Build();

    scheduler.ScheduleJob(syncJob, trigger);

}

protected override void OnStop()
{
    // true parameter indicates whether to wait for running jobs
    // to complete before completely tearing down the scheduler
    // change to false to force running jobs to abort.
    _scheduler.Shutdown(true);
}

作为旁注,您可能需要考虑使用Topshelf来帮助处理Windows服务的拆卸和设置,而不会在问题开头显示所有的锅炉板位。