[英]Adding and removing jobs dynamically to Quartz.NET Windows Service
[英]Quartz.net jobs seem to persist after windows service ended
我是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以調試模式運行項目時,當我停止服務時,控制台會顯示“服務已停止”,但是Quartz.net syncJob似乎一直在運行(控制台輸出繼續),為什么會這樣?
您需要更新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服務的拆除和設置,而無需在問題開始時顯示所有樣板文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.