![](/img/trans.png)
[英]C# Quartz.net scheduler job as windows service not executing though window service is running
[英]Quartz Job Scheduler in Windows Service
我有這個Windows服務項目,它的OnStart
方法看起來像這樣
protect void OnStart(string[] args)
{
IScheduler someScheduler = _schedFactory.GetScheduler(); // _schedFactory is a priva field of the service class
IJobDetail someJob = JobBuilder.Create<SomeJob>()
.WithIdentity("SomeJob")
.Build();
ITrigger someTrigger = TriggerBuilder.Create()
.StartAt(new DateTimeOffset(DateTime.UtcNow.AddSeconds(30)))
.WithSimpleSchedule(schedule => scheduler.WithIntervalInMinutes(3).RepeatForever())
.Build();
someScheduler.SchedulerJob(someJob, someTrigger);
someScheduler.Start();
}
我使用Visual Studio Developer命令提示符來安裝服務。 命令是installutil.exe
。 現在在安裝服務時,我進入任務管理器並啟動它。 OnStart
方法的頂部有Thread.Sleep(10000)
,因此我可以使用調試器設法附加到服務。 因此,附加它后,我會遍歷代碼,沒有什么特別的事情發生,我的意思是沒有例外發生。 我什至看到應該執行作業的時間及其正確性。 當我坐在調試模式下並等待作業的Execute
方法執行時,它沒有。 我的意思是,當時間到了時,Visual Studio正在加載符號,但作業本身無法執行。 可能是什么問題? 還有一件事,我正在此OnStart
方法中創建兩個作業。 的代碼是相同的。 可能是問題的原因嗎? 第二項工作有時會執行,有時卻無法執行。 我的意思是,如果它執行一次,它將每隔3分鍾執行一次,但是如果它沒有在預定的第一時間執行,則它將永遠不會執行。
您的代碼的問題是OnStart完成運行后,對調度程序的引用超出了范圍。 應該在函數外部的某個位置定義SomeScheduler,以免收集垃圾。 例如,這就是Quartz.Net服務器項目的工作方式(使用Topshelf,但我想您已經明白了。這是安裝服務的主程序。請注意,它返回對服務器的引用,以便主機可以保持對它的引用。
public static class Program
{
/// <summary>
/// Main.
/// </summary>
public static void Main()
{
HostFactory.Run(x =>
{
x.RunAsLocalSystem();
x.SetDescription(Configuration.ServiceDescription);
x.SetDisplayName(Configuration.ServiceDisplayName);
x.SetServiceName(Configuration.ServiceName);
x.Service(factory =>
{
QuartzServer server = new QuartzServer();
server.Initialize();
return server;
});
});
}
}
在QuartzServer類中,調度程序是一個實例變量:
public class QuartzServer : ServiceControl, IQuartzServer
{
private readonly ILog logger;
private ISchedulerFactory schedulerFactory;
private IScheduler scheduler; // code snipped....
}
正如@granadaCoder指出的那樣,簡單地重用提供的服務器可能會更容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.