private async Task ProcessFile(JobFile?jobFile, CancellationToken cancellationToken = default) { if (jobFile == null || jobFile.FileFound == false) { return; } try { XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(TypeLoadHelper); processor.AddJobGroupToNeverDelete(JobInitializationPluginName); processor.AddTriggerGroupToNeverDelete(JobInitializationPluginName); await processor.ProcessFileAndScheduleJobs( jobFile.FileName, jobFile.FileName, // systemId Scheduler, cancellationToken).ConfigureAwait(false); } catch (Exception e) { var message = "Could not schedule jobs and triggers from file " + jobFile.FileName + ": " + e.Message; if (FailOnSchedulingError) { throw new SchedulerException(message, e); } else { Log.ErrorException(message, e); } } }
private async Task ProcessFile(JobFile jobFile, CancellationToken cancellationToken = default(CancellationToken)) { if ((jobFile == null) || (jobFile.FileFound == false)) { return; } try { XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(TypeLoadHelper); processor.AddJobGroupToNeverDelete(JobInitializationPluginName); processor.AddTriggerGroupToNeverDelete(JobInitializationPluginName); await processor.ProcessFileAndScheduleJobs( jobFile.FileName, jobFile.FileName, // systemId Scheduler, cancellationToken).ConfigureAwait(false); } catch (Exception e) { Log.ErrorException("Error scheduling jobs: " + e.Message, e); } }
private void ProcessFile(JobFile jobFile) { if ((jobFile == null) || (jobFile.FileFound == false)) { return; } try { XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(TypeLoadHelper); processor.AddJobGroupToNeverDelete(JobInitializationPluginName); processor.AddTriggerGroupToNeverDelete(JobInitializationPluginName); processor.ProcessFileAndScheduleJobs( jobFile.FileName, jobFile.FileName, // systemId scheduler); } catch (Exception e) { var message = "Could not schedule jobs and triggers from file " + jobFile.FileName + ": " + e.Message; if (FailOnSchedulingError) { throw new SchedulerException(message, e); } else { Log.Error(message, e); } } }
static Job() { XMLSchedulingDataProcessor xMLSchedulingDataProcessor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); IScheduler scheduler = (new StdSchedulerFactory()).GetScheduler(); xMLSchedulingDataProcessor.ProcessFileAndScheduleJobs(AppDomain.CurrentDomain.BaseDirectory + "/quartz_jobs.xml", scheduler); scheduler.Start(); }
static Job() { XMLSchedulingDataProcessor xMLSchedulingDataProcessor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); IScheduler scheduler = (new StdSchedulerFactory()).GetScheduler(); xMLSchedulingDataProcessor.ProcessFileAndScheduleJobs(IOHelper.GetMapPath("/quartz_jobs.xml"), scheduler); scheduler.Start(); }
public void Start() { if (!IsStop) { return; } if (sched != null && !sched.IsShutdown) { IsStop = true; return; } sf = new StdSchedulerFactory(); processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); try { if (sf.GetScheduler(Name) == null) { sched = sf.GetScheduler(); } else { sched = sf.GetScheduler(Name); } processor.ProcessFileAndScheduleJobs(JobsConfigPath, sched); if (GlobalJobListener == null) { if (GlobalBeforeExecuted != null || GlobalAfterExecuted != null) { GlobalJobListener = new QuartzJobsListener(Name, GlobalBeforeExecuted, GlobalAfterExecuted); } } if (GlobalJobListener != null) { if (sched.ListenerManager.GetJobListener(Name) == null) { sched.ListenerManager.AddJobListener(GlobalJobListener, null); } } sched.Start(); IsStop = false; } catch (Exception ex) { Log.Error(ex.ToString()); if (sched != null && sched.IsShutdown) { Start(); } } Log.Info(string.Concat("QuartzScheduler:“", Name, "”启动!", JobsConfigPath)); }
public void TesDirectivesNoOverwriteWithIgnoreDups() { // create temp file string tempFileName = XMLSchedulingDataProcessor.QuartzXmlFileName; using (TextWriter writer = new StreamWriter(tempFileName, false)) { using (StreamReader reader = new StreamReader(ReadJobXmlFromEmbeddedResource("directives_overwrite_no-ignoredups.xml"))) { writer.Write(reader.ReadToEnd()); writer.Flush(); writer.Close(); } } IScheduler scheduler = null; try { StdSchedulerFactory factory = new StdSchedulerFactory(); scheduler = StdSchedulerFactory.GetDefaultScheduler(); // Setup existing job with same names as in xml data. IJobDetail job = JobBuilder.Create <NoOpJob>() .WithIdentity("job1") .Build(); ITrigger trigger = TriggerBuilder.Create() .WithIdentity("job1") .WithSchedule(SimpleScheduleBuilder.RepeatHourlyForever()).Build(); scheduler.ScheduleJob(job, trigger); job = JobBuilder.Create <NoOpJob>() .WithIdentity("job2") .Build(); trigger = TriggerBuilder.Create().WithIdentity("job2").WithSchedule(SimpleScheduleBuilder.RepeatHourlyForever()).Build(); scheduler.ScheduleJob(job, trigger); // Now load the xml data with directives: overwrite-existing-data=false, ignore-duplicates=true ITypeLoadHelper loadHelper = new SimpleTypeLoadHelper(); loadHelper.Initialize(); XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(loadHelper); processor.ProcessFileAndScheduleJobs(tempFileName, scheduler); Assert.AreEqual(2, scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("DEFAULT")).Count); Assert.AreEqual(2, scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("DEFAULT")).Count); } finally { if (scheduler != null) { scheduler.Shutdown(); } } }
public ServiceRunner() { // 从配置中读取计划执行策略 XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); ISchedulerFactory sf = new StdSchedulerFactory(); scheduler = sf.GetScheduler(); // quartz_jobs.xml文件路径 processor.ProcessFileAndScheduleJobs("~/Configs/quartz_jobs.xml", scheduler); }
// 手動加載配置文件 public void Test04() { XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); ISchedulerFactory sf = new StdSchedulerFactory(); IScheduler scheduler = sf.GetScheduler(); processor.ProcessFileAndScheduleJobs("~/quartz.xml", scheduler); scheduler.Start(); scheduler.Shutdown(); }
public static void State() { //开启调度 JobBase.Scheduler.Start(); XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); processor.ProcessFileAndScheduleJobs("~/Jobs.xml", JobBase.Scheduler); // 第一个参数是你要执行的工作(job) 第二个参数是这个工作所对应的触发器(Trigger)(例如:几秒或几分钟执行一次) //JobBase.AddSchedule(new JobServer<AddMassagejob>(), // new AddMasagerTriggerServer().AddMasagerTrigger(), "每隔五分钟向文本中写入文字", "消息工作"); }
static JobScheduler() { try { XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); StdSchedulerFactory factory = new StdSchedulerFactory(); scheduler = factory.GetScheduler().GetAwaiter().GetResult(); processor.ProcessFileAndScheduleJobs("~/quartz_jobs.xml", scheduler); } catch (System.Exception ex) { Logger.Error(ex, $"任务加载异常。"); } }
private async Task RestartScheduler() { if (_scheduler != null && _scheduler.IsStarted) { await _scheduler.Standby(); _scheduler = null; } XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); _scheduler = await _schedulerFactory.GetScheduler(); await processor.ProcessFileAndScheduleJobs("~/quartz_jobs.xml", _scheduler); await _scheduler.Start(); }
public async Task Start(DispatcherConfigModel config) { if (config.EnableLog) { var logProvider = _serviceProvider.GetService <ILogProvider>(); if (logProvider != null) { LogProvider.SetCurrentLogProvider(logProvider); } } _scheduler = await _scheduleManager.BuildScheduler(config.SchedulerConfig); var processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); await processor.ProcessFileAndScheduleJobs(config.DispatcherConfigFilePath, _scheduler); await _scheduler.Start(); }
public void Init() { if (sched != null && !sched.IsShutdown) { return; } sched = sf.GetScheduler(); var path = PathTool.getInstance().Map(JobsConfigPath); processor.ProcessFileAndScheduleJobs(path, sched); if (GlobalJobListener != null) { if (sched.ListenerManager.GetJobListener(GlobalJobListener.Name) == null) { sched.ListenerManager.AddJobListener(GlobalJobListener, null); } } }
static void Main(string[] args) { XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); //1.首先创建一个作业调度池 ISchedulerFactory schedf = new StdSchedulerFactory(); IScheduler sched = schedf.GetScheduler(); //2.创建出来一个具体的作业 // IJobDetail job = JobBuilder.Create<JobDemo>().Build(); //3.创建并配置一个触发器 // ISimpleTrigger trigger = WithIntervalInSeconds(); //4.加入作业调度池中 // sched.ScheduleJob(job, trigger); #region 读取xml文件,去掉,2,3,4 processor.ProcessFileAndScheduleJobs(AppDomain.CurrentDomain.BaseDirectory + "quartz_jobs.xml", sched); //Stream s = new StreamReader(AppDomain.CurrentDomain.BaseDirectory+"quartz_jobs.xml").BaseStream; //processor.ProcessStream(s, null); //processor.ScheduleJobs(sched); #endregion //5.开始运行 sched.Start(); Console.ReadKey(); }
private void ProcessFile(JobFile jobFile) { if ((jobFile == null) || (jobFile.FileFound == false)) { return; } try { XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(TypeLoadHelper); processor.AddJobGroupToNeverDelete(JobInitializationPluginName); processor.AddTriggerGroupToNeverDelete(JobInitializationPluginName); processor.ProcessFileAndScheduleJobs( jobFile.FileName, jobFile.FileName, // systemId scheduler); } catch (Exception) { } }
public void Start() { if (!File.Exists(ConfigHelper.QuartzSchedulerFile)) { return; } Task.Run(async() => { ISchedulerFactory sf = new StdSchedulerFactory(); _scheduler = await sf.GetScheduler(); string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigHelper.QuartzSchedulerFile); XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); await processor.ProcessFileAndScheduleJobs(path, _scheduler); // ÉèÖüàÌýÆ÷ JobListener listener = new JobListener(); //IMatcher<JobKey> matcher = KeyMatcher<JobKey>.KeyEquals(key); //sched.ListenerManager.AddJobListener(listener, matcher); _scheduler.ListenerManager.AddJobListener(listener); await _scheduler.Start(); }); }
private void ProcessFile(JobFile jobFile) { if ((jobFile == null) || (jobFile.FileFound == false)) { return; } try { XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(TypeLoadHelper); processor.AddJobGroupToNeverDelete(JobInitializationPluginName); processor.AddTriggerGroupToNeverDelete(JobInitializationPluginName); processor.ProcessFileAndScheduleJobs( jobFile.FileName, jobFile.FileName, // systemId scheduler); } catch (Exception e) { Log.Error("Error scheduling jobs: " + e.Message, e); } }
/// <summary> /// Register jobs and triggers (within a transaction, if possible). /// </summary> protected virtual void RegisterJobsAndTriggers() { ITransactionStatus transactionStatus = null; if (transactionManager != null) { transactionStatus = transactionManager.GetTransaction(new DefaultTransactionDefinition()); } try { if (jobSchedulingDataLocations != null) { XMLSchedulingDataProcessor dataProcessor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); dataProcessor.OverWriteExistingData = overwriteExistingJobs; foreach (string location in jobSchedulingDataLocations) { dataProcessor.ProcessFileAndScheduleJobs(location, GetScheduler()); } } // Register JobDetails. if (jobDetails != null) { foreach (IJobDetail jobDetail in jobDetails) { AddJobToScheduler(jobDetail); } } else { // Create empty list for easier checks when registering triggers. jobDetails = new LinkedList(); } // Register Calendars. if (calendars != null) { foreach (DictionaryEntry entry in calendars) { string calendarName = (string)entry.Key; ICalendar calendar = (ICalendar)entry.Value; GetScheduler().AddCalendar(calendarName, calendar, true, true); } } // Register Triggers. if (triggers != null) { foreach (ITrigger trigger in triggers) { AddTriggerToScheduler(trigger); } } } catch (Exception ex) { if (transactionStatus != null) { try { transactionManager.Rollback(transactionStatus); } catch (TransactionException) { logger.Error("Job registration exception overridden by rollback exception", ex); throw; } } if (ex is SchedulerException) { throw; } throw new SchedulerException("Registration of jobs and triggers failed: " + ex.Message); } if (transactionStatus != null) { transactionManager.Commit(transactionStatus); } }
public async Task TestOverwriteFlag() { // create temp file string tempFileName = XMLSchedulingDataProcessor.QuartzXmlFileName; // Use File.Create (as opposed to File.OpenWrite) so that if the file already exists, it will be completely // replaced instead of only overwriting the first N bytes (where N is the length of SimpleJobTrigger.xml) using (TextWriter writer = new StreamWriter(File.Create(tempFileName))) { using (StreamReader reader = new StreamReader(ReadJobXmlFromEmbeddedResource("SimpleJobTrigger.xml"))) { await writer.WriteAsync(await reader.ReadToEndAsync()); await writer.FlushAsync(); } } IScheduler scheduler = null; try { var properties = new NameValueCollection(); properties["quartz.serializer.type"] = TestConstants.DefaultSerializerType; StdSchedulerFactory factory = new StdSchedulerFactory(properties); scheduler = await factory.GetScheduler(); // Let's setup a fixture job data that we know test is not going modify it. IJobDetail job = JobBuilder.Create <NoOpJob>() .WithIdentity("job1").UsingJobData("foo", "dont_chg_me").Build(); ITrigger trigger = TriggerBuilder.Create().WithIdentity("job1").WithSchedule(SimpleScheduleBuilder.RepeatHourlyForever()).Build(); await scheduler.ScheduleJob(job, trigger); XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); try { await processor.ProcessFileAndScheduleJobs(scheduler, false); Assert.Fail("OverWriteExisting flag didn't work. We should get Exception when overwrite is set to false."); } catch (ObjectAlreadyExistsException) { // This is expected. Do nothing. } // We should still have what we start with. var jobKeys = await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("DEFAULT")); Assert.AreEqual(1, jobKeys.Count); var triggerKeys = await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("DEFAULT")); Assert.AreEqual(1, triggerKeys.Count); job = await scheduler.GetJobDetail(JobKey.Create("job1")); string fooValue = job.JobDataMap.GetString("foo"); Assert.AreEqual("dont_chg_me", fooValue); } finally { if (File.Exists(tempFileName)) { File.Delete(tempFileName); } // shutdown scheduler if (scheduler != null) { await scheduler.Shutdown(); } } }
public void TestOverwriteFlag() { // create temp file string tempFileName = XMLSchedulingDataProcessor.QuartzXmlFileName; using (TextWriter writer = new StreamWriter(tempFileName, false)) { using (StreamReader reader = new StreamReader(ReadJobXmlFromEmbeddedResource("SimpleJobTrigger.xml"))) { writer.Write(reader.ReadToEnd()); writer.Flush(); writer.Close(); } } IScheduler scheduler = null; try { StdSchedulerFactory factory = new StdSchedulerFactory(); scheduler = StdSchedulerFactory.GetDefaultScheduler(); // Let's setup a fixture job data that we know test is not going modify it. IJobDetail job = JobBuilder.Create<NoOpJob>() .WithIdentity("job1").UsingJobData("foo", "dont_chg_me").Build(); ITrigger trigger = TriggerBuilder.Create().WithIdentity("job1").WithSchedule(SimpleScheduleBuilder.RepeatHourlyForever()).Build(); scheduler.ScheduleJob(job, trigger); XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); try { processor.ProcessFileAndScheduleJobs(scheduler, false); Assert.Fail("OverWriteExisting flag didn't work. We should get Exception when overwrite is set to false."); } catch (ObjectAlreadyExistsException) { // This is expected. Do nothing. } // We should still have what we start with. Assert.AreEqual(1, scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals("DEFAULT")).Count); Assert.AreEqual(1, scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEquals("DEFAULT")).Count); job = scheduler.GetJobDetail(JobKey.Create("job1")); String fooValue = job.JobDataMap.GetString("foo"); Assert.AreEqual("dont_chg_me", fooValue); } finally { if (File.Exists(tempFileName)) { File.Delete(tempFileName); } // shutdown scheduler if (scheduler != null) { scheduler.Shutdown(); } } }
public async static Task Init() { #region 自定义框架日志 LogProvider.SetCurrentLogProvider(new CustomLogProvider()); #endregion #region scheduler 创建单元/实例 //Console.WriteLine("初始化scheduler......"); //StdSchedulerFactory factory = new StdSchedulerFactory(); //IScheduler scheduler = await factory.GetScheduler(); IScheduler scheduler = await ScheduleManager.BuildScheduler(); { //使用配置文件 XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); //quartz_jobs.xml右键属性设置为‘始终复杂’ await processor.ProcessFileAndScheduleJobs("~/CfgFiles/quartz_jobs.xml", scheduler); } { //添加ISchedulerListener监听 scheduler.ListenerManager.AddSchedulerListener(new CustomSchedulerListener()); //添加IJobListener监听 scheduler.ListenerManager.AddJobListener(new CustomJobListener()); //添加ITriggerListener监听 scheduler.ListenerManager.AddTriggerListener(new CustomTriggerListener()); } await scheduler.Start(); #endregion #region 通过quartz_jobs.xml配置文件后,这里就可以不需要了,如果在需要传参的情况下可以考虑使用以下方式 ////1 //{ // #region Job 创建作业 // //创建作业 // IJobDetail jobDetail = JobBuilder.Create<TestJob>() // .WithIdentity("TestJob", "Group1")//分组必须一致 // .WithDescription("This is TestJob") // .Build(); // //jobDetail传参 // jobDetail.JobDataMap.Add("parameter1", "table1"); // jobDetail.JobDataMap.Add("parameter2", "table2"); // jobDetail.JobDataMap.Add("parameter3", 333); // jobDetail.JobDataMap.Add("Year", DateTime.Now.Year); // #endregion // #region Trigger 创建时间策略 // ////创建时间策略 Cron // //ITrigger trigger = TriggerBuilder.Create() // // .WithIdentity("testtrigger1", "group1") // // //.StartAt(new DateTimeOffset(DateTime.Now.AddSeconds(5))) //5秒后启动 // // .StartNow()//立即启动 // // //.WithCronSchedule("0 0/1 * * * ?")//每隔一分钟 // // .WithCronSchedule("0/10 * * * * ?")//每隔10秒运行一次 // // .WithDescription("This is TestJob's Trigger") // // .Build(); // //创建时间策略 Simple // ITrigger trigger = TriggerBuilder.Create() // .WithIdentity("TestJobTrigger1", "Group1")//分组必须一致 // //.StartNow()//立即启动 // .StartAt(new DateTimeOffset(DateTime.Now.AddSeconds(5)))//5秒后启动 // .WithSimpleSchedule(x => x // .WithIntervalInSeconds(10) //10秒循环一次 // .RepeatForever()//一直执行 // //.WithRepeatCount(2) //只循环10次 // ) // .WithDescription("This is TestJob's Trigger") // .Build(); // //trigger传参 // trigger.JobDataMap.Add("parameter5", "存储过程"); // trigger.JobDataMap.Add("parameter6", "222000"); // trigger.JobDataMap.Add("parameter7", 333000); // trigger.JobDataMap.Add("Year", DateTime.Now.Year + 10);//加一下试试 // #endregion // await scheduler.ScheduleJob(jobDetail, trigger); // Console.WriteLine("scheduler作业添加完成......"); //} ////2 //{ // #region Job 创建作业 // //创建作业 // IJobDetail jobDetail = JobBuilder.Create<GoodJob>() // .WithIdentity("GoodJob", "Group2")//分组必须一致 // .WithDescription("This is GoodJob") // .Build(); // #endregion // #region Trigger 创建时间策略 // //创建时间策略 Cron // ITrigger trigger = TriggerBuilder.Create() // .WithIdentity("GoodJobTrigger1", "Group2")//分组必须一致 // .StartAt(new DateTimeOffset(DateTime.Now.AddSeconds(10))) //10秒后启动 // //.StartNow()//立即启动 // //.WithCronSchedule("0 0/1 * * * ?")//每隔一分钟 // .WithCronSchedule("0/10 * * * * ?")//每隔10秒运行一次 // .WithDescription("This is GoodJob's Trigger") // .Build(); // #endregion // await scheduler.ScheduleJob(jobDetail, trigger); // Console.WriteLine("scheduler作业添加完成......"); //} #endregion }
public void TestOverwriteFlag() { // create temp file string tempFileName = XMLSchedulingDataProcessor.QuartzXmlFileName; using (TextWriter writer = new StreamWriter(tempFileName, false)) { using (StreamReader reader = new StreamReader(ReadJobXmlFromEmbeddedResource("SimpleJobTrigger.xml"))) { writer.Write(reader.ReadToEnd()); writer.Flush(); writer.Close(); } } IScheduler scheduler = null; try { StdSchedulerFactory factory = new StdSchedulerFactory(); scheduler = StdSchedulerFactory.GetDefaultScheduler(); // Let's setup a fixture job data that we know test is not going modify it. IJobDetail job = JobBuilder.Create <NoOpJob>() .WithIdentity("job1").UsingJobData("foo", "dont_chg_me").Build(); ITrigger trigger = TriggerBuilder.Create().WithIdentity("job1").WithSchedule(SimpleScheduleBuilder.RepeatHourlyForever()).Build(); scheduler.ScheduleJob(job, trigger); XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); try { processor.ProcessFileAndScheduleJobs(scheduler, false); Assert.Fail("OverWriteExisting flag didn't work. We should get Exception when overwrite is set to false."); } catch (ObjectAlreadyExistsException) { // This is expected. Do nothing. } // We should still have what we start with. Assert.AreEqual(1, scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("DEFAULT")).Count); Assert.AreEqual(1, scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("DEFAULT")).Count); job = scheduler.GetJobDetail(JobKey.Create("job1")); String fooValue = job.JobDataMap.GetString("foo"); Assert.AreEqual("dont_chg_me", fooValue); } finally { if (File.Exists(tempFileName)) { File.Delete(tempFileName); } // shutdown scheduler if (scheduler != null) { scheduler.Shutdown(); } } }
public async Task TesDirectivesNoOverwriteWithIgnoreDups() { // create temp file string tempFileName = XMLSchedulingDataProcessor.QuartzXmlFileName; using (TextWriter writer = new StreamWriter(File.OpenWrite(tempFileName))) { using (StreamReader reader = new StreamReader(ReadJobXmlFromEmbeddedResource("directives_overwrite_no-ignoredups.xml"))) { await writer.WriteAsync(await reader.ReadToEndAsync()); await writer.FlushAsync(); } } IScheduler scheduler = null; try { NameValueCollection properties = new NameValueCollection(); properties["quartz.serializer.type"] = TestConstants.DefaultSerializerType; StdSchedulerFactory factory = new StdSchedulerFactory(properties); scheduler = await factory.GetScheduler(); // Setup existing job with same names as in xml data. IJobDetail job = JobBuilder.Create <NoOpJob>() .WithIdentity("job1") .Build(); ITrigger trigger = TriggerBuilder.Create() .WithIdentity("job1") .WithSchedule(SimpleScheduleBuilder.RepeatHourlyForever()).Build(); await scheduler.ScheduleJob(job, trigger); job = JobBuilder.Create <NoOpJob>() .WithIdentity("job2") .Build(); trigger = TriggerBuilder.Create().WithIdentity("job2").WithSchedule(SimpleScheduleBuilder.RepeatHourlyForever()).Build(); await scheduler.ScheduleJob(job, trigger); // Now load the xml data with directives: overwrite-existing-data=false, ignore-duplicates=true ITypeLoadHelper loadHelper = new SimpleTypeLoadHelper(); loadHelper.Initialize(); XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(loadHelper); await processor.ProcessFileAndScheduleJobs(tempFileName, scheduler); var jobKeys = await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("DEFAULT")); Assert.AreEqual(2, jobKeys.Count); var triggerKeys = await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("DEFAULT")); Assert.AreEqual(2, triggerKeys.Count); } finally { if (scheduler != null) { await scheduler.Shutdown(); } } }
/// <summary> /// Register jobs and triggers (within a transaction, if possible). /// </summary> protected virtual void RegisterJobsAndTriggers() { ITransactionStatus transactionStatus = null; if (transactionManager != null) { transactionStatus = transactionManager.GetTransaction(new DefaultTransactionDefinition()); } try { if (jobSchedulingDataLocations != null) { XMLSchedulingDataProcessor dataProcessor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); dataProcessor.OverWriteExistingData = overwriteExistingJobs; foreach (string location in jobSchedulingDataLocations) { dataProcessor.ProcessFileAndScheduleJobs(location, GetScheduler()); } } // Register JobDetails. if (jobDetails != null) { foreach (IJobDetail jobDetail in jobDetails) { AddJobToScheduler(jobDetail); } } else { // Create empty list for easier checks when registering triggers. jobDetails = new LinkedList(); } // Register Calendars. if (calendars != null) { foreach (DictionaryEntry entry in calendars) { string calendarName = (string) entry.Key; ICalendar calendar = (ICalendar) entry.Value; GetScheduler().AddCalendar(calendarName, calendar, true, true); } } // Register Triggers. if (triggers != null) { foreach (ITrigger trigger in triggers) { AddTriggerToScheduler(trigger); } } } catch (Exception ex) { if (transactionStatus != null) { try { transactionManager.Rollback(transactionStatus); } catch (TransactionException) { logger.Error("Job registration exception overridden by rollback exception", ex); throw; } } if (ex is SchedulerException) { throw; } throw new SchedulerException("Registration of jobs and triggers failed: " + ex.Message); } if (transactionStatus != null) { transactionManager.Commit(transactionStatus); } }
public void TesDirectivesNoOverwriteWithIgnoreDups() { // create temp file string tempFileName = XMLSchedulingDataProcessor.QuartzXmlFileName; using (TextWriter writer = new StreamWriter(tempFileName, false)) { using (StreamReader reader = new StreamReader(ReadJobXmlFromEmbeddedResource("directives_overwrite_no-ignoredups.xml"))) { writer.Write(reader.ReadToEnd()); writer.Flush(); writer.Close(); } } IScheduler scheduler = null; try { StdSchedulerFactory factory = new StdSchedulerFactory(); scheduler = StdSchedulerFactory.GetDefaultScheduler(); // Setup existing job with same names as in xml data. IJobDetail job = JobBuilder.Create<NoOpJob>() .WithIdentity("job1") .Build(); ITrigger trigger = TriggerBuilder.Create() .WithIdentity("job1") .WithSchedule(SimpleScheduleBuilder.RepeatHourlyForever()).Build(); scheduler.ScheduleJob(job, trigger); job = JobBuilder.Create<NoOpJob>() .WithIdentity("job2") .Build(); trigger = TriggerBuilder.Create().WithIdentity("job2").WithSchedule(SimpleScheduleBuilder.RepeatHourlyForever()).Build(); scheduler.ScheduleJob(job, trigger); // Now load the xml data with directives: overwrite-existing-data=false, ignore-duplicates=true ITypeLoadHelper loadHelper = new SimpleTypeLoadHelper(); loadHelper.Initialize(); XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(loadHelper); processor.ProcessFileAndScheduleJobs(tempFileName, scheduler); Assert.AreEqual(2, scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals("DEFAULT")).Count); Assert.AreEqual(2, scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEquals("DEFAULT")).Count); } finally { if (scheduler != null) { scheduler.Shutdown(); } } }
public static async Task Init() { #region 获取框架日志 LogProvider.SetCurrentLogProvider(new CustomConsoleLogProvider());// #endregion #region Scheduler //StdSchedulerFactory factory = new StdSchedulerFactory(); //IScheduler scheduler = await factory.GetScheduler(); IScheduler scheduler = await ScheduleManager.BuildScheduler(); await scheduler.Start(); #region Listener scheduler.ListenerManager.AddJobListener(new CustomJobListener()); scheduler.ListenerManager.AddTriggerListener(new CustomTriggerListener()); scheduler.ListenerManager.AddSchedulerListener(new CustomSchedulerListener()); #endregion #endregion #region JobDetail IJobDetail jobDetail = JobBuilder.Create <SendMessage>() .WithIdentity("sendJob", "group1") .WithDescription("This is sendJob") .Build(); jobDetail.JobDataMap.Add("Student1", "阳光下的微笑"); jobDetail.JobDataMap.Add("Student2", "明日梦"); jobDetail.JobDataMap.Add("Student3", "大白"); jobDetail.JobDataMap.Add("Student4", "池鱼"); jobDetail.JobDataMap.Add("Year", DateTime.Now.Year); #endregion #region trigger //ITrigger trigger = TriggerBuilder.Create() // .WithIdentity("sendTrigger", "group1") // //.StartAt(new DateTimeOffset(DateTime.Now.AddSeconds(10))) // .StartNow() // .WithCronSchedule("5/3 * * * * ?")//每隔一分钟 // //5,8,11,14 // .WithDescription("This is sendJob's sendTrigger") // .Build(); ITrigger trigger = TriggerBuilder.Create() .WithIdentity("sendTrigger", "group1") .StartNow() .WithSimpleSchedule(x => x .WithIntervalInSeconds(10) //多少秒执行一次 .WithRepeatCount(10) //表示最多执行多少次 .RepeatForever()) .WithDescription("This is testjob's Trigger") .Build(); trigger.JobDataMap.Add("Student5", "非常Nice"); trigger.JobDataMap.Add("Student6", "Jerry"); trigger.JobDataMap.Add("Student7", "龙"); trigger.JobDataMap.Add("Student8", "月光寒"); trigger.JobDataMap.Add("Year", DateTime.Now.Year + 1); #endregion await scheduler.ScheduleJob(jobDetail, trigger); { { //使用配置文件 XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper()); await processor.ProcessFileAndScheduleJobs("~/CfgFiles/quartz_jobs.xml", scheduler); } } { //IJobDetail sayHijobDetail = JobBuilder.Create<SayHIJob>() // .WithDescription("this is sayHijobDetail") //.WithIdentity("SayhiJob", "Vip高级班") //.WithDescription("This is SayhiJob") //.Build(); //ITrigger SayhiTrigger = TriggerBuilder.Create() // .WithIdentity("SayhiTrigger", "Vip高级班") // //.StartAt(new DateTimeOffset(DateTime.Now.AddSeconds(10))) // .StartNow() // .WithCronSchedule("1/4 * * * * ?") // .WithDescription("This is SayhiJob's SayhiTrigger") // .Build(); //await scheduler.ScheduleJob(sayHijobDetail, SayhiTrigger); } }