Zabaa
Zabaa

Reputation: 329

Shutdown service from QuartzJob

I use TopShelf for build windows service and TopShelf.Quartz package. Is it possible to shutdown whole service from Execute method of IJob ? Right now all I can do is delete job. E.g if I catch specific exception in job I would like to make log and shutdown service.

Thanks for any answer.

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

Upvotes: 1

Views: 729

Answers (1)

Backs
Backs

Reputation: 24903

You name context, and you can get your scheduler and shutdown it

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

On documentation page there is example of stopping whole service (if i'm not mistaken):

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

Upvotes: 1

Related Questions