2015-08-13 58 views
1

我使用TopShelf構建windows服務和TopShelf.Quartz包。 是否可以從IJob的Execute方法關閉整個服務?現在我所能做的就是刪除工作。例如,如果我在工作中發現特定異常,我想進行日誌和關閉服務。QuartzJob的關閉服務

感謝您的任何答案。

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 
    } 
} 

回答

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()); 
}); 
+0

感謝您的回答,但我希望關閉整個服務,而不僅僅是調度程序。我不知道如何發送信息從石英到頂部關於那個異常和shoutdown服務 – Zabaa

+0

@Zabaa看看這裏的例子https://github.com/dtinteractive/Topshelf.Integrations,看來,最後一個是你的情況。此外,更新的答案 – Backs

+1

這,但讓你的服務實現ServiceControl,並讓Topshelf調用這些方法,而不是使用上面的代表。然後,當你想停止時,調用HostControl.Stop()。 HostControl是ServiceControl的Start方法的參數。 –