【问题标题】:Shutdown service from QuartzJobQuartzJob 的关闭服务
【发布时间】:2015-08-13 09:37:50
【问题描述】:

我使用 TopShelf 构建 windows 服务和 TopShelf.Quartz 包。 是否可以从 IJob 的 Execute 方法关闭整个服务?现在我能做的就是删除工作。例如,如果我在工作中发现特定异常,我想创建日志和关闭服务。

感谢您的任何回答。

public class Program
{
   public static void Main()
   {
     HostFactory.Run(c =>
     {
        // Topshelf.Ninject (Optional) - Initiates Ninject and consumes Modules
        c.UseNinject(new SampleModule());

        c.Service<SampleService>(s =>
        {
            //Topshelf.Ninject (Optional) - Construct service using Ninject
            s.ConstructUsingNinject();

            s.WhenStarted((service, control) => service.Start());
            s.WhenStopped((service, control) => service.Stop());

            // Topshelf.Quartz.Ninject (Optional) - Construct IJob instance with Ninject
            s.UseQuartzNinject(); 

            // Schedule a job to run in the background every 5 seconds.
            // The full Quartz Builder framework is available here.
            s.ScheduleQuartzJob(q =>
                q.WithJob(() =>
                    JobBuilder.Create<SampleJob>().Build())
                .AddTrigger(() =>
                    TriggerBuilder.Create()
                        .WithSimpleSchedule(builder => builder
                            .WithIntervalInSeconds(5)
                            .RepeatForever())
                        .Build())
                );
        });
    });
  }
}

public class SampleJob : IJob
{
    public void Execute(IJobExecutionContext context)
    {
        //Here I want catch exception and shoutdown service
    }
}

【问题讨论】:

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


    【解决方案1】:

    你的名字是context,你可以得到你的调度器并关闭它

    public class SampleJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            context.Scheduler.Shutdown();
        }
    }
    

    documentation 页面上有停止整个服务的示例(如果我没记错的话):

    c.Service<SampleService>(s =>
    {
        //Specifies that Topshelf should delegate to Ninject for construction
        s.ConstructUsingNinject();
    
        s.WhenStarted((service, control) => service.Start());
        s.WhenStopped((service, control) => service.Stop());
    });
    

    【讨论】:

    • 感谢您的回答,但我想关闭整个服务而不仅仅是调度程序。我不知道如何将有关该异常和喊叫服务的信息从石英发送到顶级货架
    • @Zabaa 看看这里的例子github.com/dtinteractive/Topshelf.Integrations,看来,最后一个是你的情况。另外,更新答案
    • 这个,但是让你的服务实现ServiceControl,让Topshelf调用这些方法而不是使用上面的委托。然后,当您想停止时,调用 HostControl.Stop()。 HostControl 是 ServiceControl 的 Start 方法的参数。
    猜你喜欢
    • 2018-05-10
    • 2018-04-26
    • 2010-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多