static async void ThridTriggers() { //构造一个策略工厂 //NameValueCollection props = new NameValueCollection { // {"quartz.serializer.type","binary" } //}; HolidayCalendar cal = new HolidayCalendar(); cal.AddExcludedDate(DateTime.Now); StdSchedulerFactory factory = new StdSchedulerFactory(); //获取一个策略 IScheduler sched = await factory.GetScheduler(); await sched.AddCalendar("myholiday", cal, false, false); //开始策略 await sched.Start(); //设置一个任务 IJobDetail job = JobBuilder.Create <DumbJob>().WithIdentity("myjob", "group1").UsingJobData("jobSays", "Hello world!").UsingJobData("myFloatValue", 3.1415f).Build(); //设置任务触发条件 ITrigger trigger = TriggerBuilder.Create().WithIdentity("myTrigger", "group1").StartNow().WithSimpleSchedule(x => x.WithIntervalInSeconds(2).RepeatForever()).ModifiedByCalendar("myholiday").Build(); //将任务加入任务列表 await sched.ScheduleJob(job, trigger); }
private static HolidayCalendar GetHolidayCalendar() { HolidayCalendar _calendar = null; var _calendarResult = SalaryHandler.Instance.SalaryClient.GetHolidayCalendars(SalaryHandler.Instance.Token); foreach (var _apiMessage in _calendarResult.Messages) { if (Logger.IsDebugEnabled) { Logger.Debug(_apiMessage.Message); } } if (_calendarResult.ResponseState == TransactionalApi.SDK.SalaryService.ExecutionStatus.Success) { _calendar = _calendarResult.Return.FirstOrDefault(); } if (_calendar == null) { throw new ArgumentException("No holiday calendar found"); } if (Logger.IsDebugEnabled) { Logger.Debug("Calendar selected: " + _calendar.Name); } return(_calendar); }
//------------------------------------------------------------------------- /// <summary> /// Adjusts the date, adding the tenor and then applying the business day adjustment. /// <para> /// The calculation is performed in two steps. /// </para> /// <para> /// Step one, use <seealso cref="PeriodAdditionConvention#adjust(LocalDate, Period, HolidayCalendar)"/> to add the period. /// </para> /// <para> /// Step two, use <seealso cref="BusinessDayAdjustment#adjust(LocalDate, ReferenceData)"/> to adjust the result of step one. /// /// </para> /// </summary> /// <param name="date"> the date to adjust </param> /// <param name="refData"> the reference data, used to find the holiday calendar </param> /// <returns> the adjusted date </returns> public LocalDate adjust(LocalDate date, ReferenceData refData) { HolidayCalendar holCal = adjustment.Calendar.resolve(refData); BusinessDayConvention bda = adjustment.Convention; return(bda.adjust(additionConvention.adjust(date, tenor.Period, holCal), holCal)); }
// creates an observation private FxIndexObservation create(LocalDate fixingDate, HolidayCalendar fixingCal, DateAdjuster maturityAdjuster) { LocalDate fixingBusinessDay = fixingCal.nextOrSame(fixingDate); LocalDate maturityDate = maturityAdjuster.adjust(fixingBusinessDay); return(new FxIndexObservation(this, fixingDate, maturityDate)); }
//------------------------------------------------------------------------- // Compute the approximated rate in the case where the whole period is forward. // There is no need to compute overnight periods, except for the cut-off period. private double rateForward(OvernightAveragedRateComputation computation, OvernightIndexRates rates) { OvernightIndex index = computation.Index; HolidayCalendar calendar = computation.FixingCalendar; LocalDate startFixingDate = computation.StartDate; LocalDate endFixingDateP1 = computation.EndDate; LocalDate endFixingDate = calendar.previous(endFixingDateP1); LocalDate onRateEndDate = computation.calculateMaturityFromFixing(endFixingDate); LocalDate onRateStartDate = computation.calculateEffectiveFromFixing(startFixingDate); LocalDate onRateNoCutOffEndDate = onRateEndDate; int cutoffOffset = computation.RateCutOffDays > 1 ? computation.RateCutOffDays : 1; double accumulatedInterest = 0.0d; double accrualFactorTotal = index.DayCount.yearFraction(onRateStartDate, onRateEndDate); if (cutoffOffset > 1) { // Cut-off period LocalDate currentFixingDate = endFixingDate; OvernightIndexObservation lastIndexObs = null; double cutOffAccrualFactorTotal = 0d; for (int i = 1; i < cutoffOffset; i++) { currentFixingDate = calendar.previous(currentFixingDate); lastIndexObs = computation.observeOn(currentFixingDate); onRateNoCutOffEndDate = lastIndexObs.MaturityDate; cutOffAccrualFactorTotal += lastIndexObs.YearFraction; } double forwardRateCutOff = rates.rate(lastIndexObs); accumulatedInterest += cutOffAccrualFactorTotal * forwardRateCutOff; } // Approximated part accumulatedInterest += approximatedInterest(computation.observeOn(onRateStartDate), onRateNoCutOffEndDate, rates); // final rate return(accumulatedInterest / accrualFactorTotal); }
public virtual void test_combineWith_none() { HolidayCalendar @base = new MockHolCal(); HolidayCalendar test = @base.combinedWith(HolidayCalendars.NO_HOLIDAYS); assertSame(test, @base); }
public virtual void test_combineWith_same() { HolidayCalendar @base = new MockHolCal(); HolidayCalendar test = @base.combinedWith(@base); assertSame(test, @base); }
/// <summary> /// Creates an instance. </summary> /// <param name="calendar1"> the value of the property, not null </param> /// <param name="calendar2"> the value of the property, not null </param> internal CombinedHolidayCalendar(HolidayCalendar calendar1, HolidayCalendar calendar2) { JodaBeanUtils.notNull(calendar1, "calendar1"); JodaBeanUtils.notNull(calendar2, "calendar2"); this.calendar1 = calendar1; this.calendar2 = calendar2; }
private static ICalendar GetCalendar() { var bankHolidayCalendar = new HolidayCalendar(); bankHolidayCalendar.AddExcludedDate(DateTime.Today.AddDays(1)); return(bankHolidayCalendar); }
/// <summary> /// Resolves this adjustment using the specified reference data, returning an adjuster. /// <para> /// This returns a <seealso cref="DateAdjuster"/> that performs the same calculation as this adjustment. /// It binds the holiday calendar, looked up from the reference data, into the result. /// As such, there is no need to pass the reference data in again. /// /// </para> /// </summary> /// <param name="refData"> the reference data, used to find the holiday calendar </param> /// <returns> the adjuster, bound to a specific holiday calendar </returns> public DateAdjuster resolve(ReferenceData refData) { HolidayCalendar holCal = adjustment.Calendar.resolve(refData); BusinessDayConvention bda = adjustment.Convention; return(date => bda.adjust(additionConvention.adjust(date, period, holCal), holCal)); }
public QueryResponse Put(Guid id, [FromBody] HolidayCalendar model) { Logger.DebugFormat("Entered HolidayCalendarsController.Put(). Calendar id = {0}", id); var response = new QueryResponse { Valid = true }; try { _schedulerCore.AmendHolidayCalendar(id, model.Description, model.DatesExcluded); } catch (Exception ex) { response.Valid = false; response.Errors = new List <Error> { new Error { Code = "ErrorEditingHolidayCalendar", Type = "Server", Message = string.Format("Error: {0}", ex.Message) } }; } return(response); }
/// <summary> /// HolidayCalendar 排除某一天的任务的执行(如果涉及到同一天跨年的情况,需要多次添加不同年份) /// </summary> public static void Fun13() { var sche = StdSchedulerFactory.GetDefaultScheduler(); sche.Start(); HolidayCalendar cale = new HolidayCalendar(); cale.AddExcludedDate(DateTime.Now.AddYears(-1)); //排除去年的今天不处理 cale.AddExcludedDate(DateTime.Now); //排除今天不处理 sche.AddCalendar("myCalendar", cale, true, true); var job = JobBuilder.Create <MyJob>() .Build(); var trigger = TriggerBuilder.Create().StartNow().WithDailyTimeIntervalSchedule( m => m.StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(7, 0)) .EndingDailyAt(TimeOfDay.HourAndMinuteOfDay(19, 0)) .WithIntervalInSeconds(1) .Build() //是任务在7点-19点间执行,执行频率:每秒执行一次 ) .ModifiedByCalendar("myCalendar") .Build(); //ModifiedByCalendar 将ICalendar的设置应用到触发器中 sche.ScheduleJob(job, trigger); }
public QueryResponse Post([FromBody] HolidayCalendar model) { Logger.DebugFormat("Entered HolidayCalendarsController.Post(). Calendar Name = {0}", model.Name); var response = new QueryResponse { Valid = true }; try { var id = _schedulerCore.AddHolidayCalendar(model.Name, model.Description, model.DatesExcluded); response.Id = id; } catch (Exception ex) { response.Valid = false; response.Errors = new List <Error> { new Error { Code = "ErrorCreatingHolidayCalendar", Type = "Server", Message = string.Format("Error: {0}", ex.Message) } }; } return(response); }
public static async Task StartScheduler() { LogProvider.SetCurrentLogProvider(new ConsoleLogProvider()); // Grab the Scheduler instance from the Factory StdSchedulerFactory factory = new StdSchedulerFactory(); IScheduler scheduler = await factory.GetScheduler(); // and start it off await scheduler.Start(); // define the job and tie it to our HelloJob class IJobDetail job = JobBuilder.Create <PublishScheduledPostsJob>() .WithIdentity("job1", "group1") .Build(); // Trigger the job to run now, and then repeat every 10 seconds ITrigger trigger = TriggerBuilder.Create() .WithIdentity("trigger1", "group1") .StartNow() .WithSimpleSchedule(x => x .WithIntervalInSeconds(10) .RepeatForever()) .Build(); HolidayCalendar holidayCalendar = new HolidayCalendar(); // Tell quartz to schedule the job using our trigger await scheduler.ScheduleJob(job, trigger); }
private IList <HolidayCalendar> GenerateNewList(int mm, int yy) { IList <HolidayCalendar> List = new List <HolidayCalendar>(); DateTime sDate = new DateTime(yy, mm, 1); DateTime eDate = sDate.AddMonths(1); try { while (sDate < eDate) { HolidayCalendar h = new HolidayCalendar { WorkingDate = Convert.ToDateTime(sDate), Day = sDate.DayOfWeek.ToString(), day_type_code = "WR" }; List.Add(h); sDate = sDate.AddDays(1.0); } } catch (Exception ex) { //bool false = BusinessLogicExceptionHandler.HandleException(ref ex); if (false) { throw ex; } } return(List); }
/// <summary> /// Restricted copy constructor. </summary> /// <param name="beanToCopy"> the bean to copy from, not null </param> internal Builder(OvernightAveragedDailyRateComputation beanToCopy) { this.index_Renamed = beanToCopy.Index; this.fixingCalendar_Renamed = beanToCopy.FixingCalendar; this.startDate_Renamed = beanToCopy.StartDate; this.endDate_Renamed = beanToCopy.EndDate; }
//------------------------------------------------------------------------- public virtual void test_combinedWith() { HolidayCalendar base1 = new MockHolCal(); HolidayCalendar base2 = HolidayCalendars.FRI_SAT; HolidayCalendar test = base1.combinedWith(base2); assertEquals(test.ToString(), "HolidayCalendar[Fri/Sat+Mock]"); assertEquals(test.Name, "Fri/Sat+Mock"); assertEquals(test.Equals(base1.combinedWith(base2)), true); assertEquals(test.Equals(ANOTHER_TYPE), false); assertEquals(test.Equals(null), false); assertEquals(test.GetHashCode(), base1.combinedWith(base2).GetHashCode()); assertEquals(test.isHoliday(THU_2014_07_10), false); assertEquals(test.isHoliday(FRI_2014_07_11), true); assertEquals(test.isHoliday(SAT_2014_07_12), true); assertEquals(test.isHoliday(SUN_2014_07_13), true); assertEquals(test.isHoliday(MON_2014_07_14), false); assertEquals(test.isHoliday(TUE_2014_07_15), false); assertEquals(test.isHoliday(WED_2014_07_16), true); assertEquals(test.isHoliday(THU_2014_07_17), false); assertEquals(test.isHoliday(FRI_2014_07_18), true); assertEquals(test.isHoliday(SAT_2014_07_19), true); assertEquals(test.isHoliday(SUN_2014_07_20), true); assertEquals(test.isHoliday(MON_2014_07_21), false); }
public System.Func <LocalDate, FxIndexObservation> resolve(ReferenceData refData) { HolidayCalendar fixingCal = fixingCalendar.resolve(refData); DateAdjuster maturityAdj = maturityDateOffset.resolve(refData); return(fixingDate => create(fixingDate, fixingCal, maturityAdj)); }
public void ShouldAddExclusionDatesToExistingHolidayCalendar() { // Arrange Guid calId = Guid.NewGuid(); const string calName = "TestHolCal"; var exclusionDate1 = new DateTime(2016, 01, 01); var exclusionDate2 = new DateTime(2016, 01, 02); _mockPersistanceStore.Setup(m => m.GetCalendarName(calId)).Returns(calName); var registeredCalendar = new HolidayCalendar(); registeredCalendar.AddExcludedDate(exclusionDate1); _mockScheduler.Setup(i => i.GetCalendar(calName)).Returns(registeredCalendar); ISchedulerCore schedulerCore = new SchedulerCore(_mockScheduler.Object, _mockPersistanceStore.Object); // Act schedulerCore.AddHolidayCalendarExclusionDates(calId, new List <DateTime> { exclusionDate1, exclusionDate2 }); // Assert _mockScheduler.Verify( x => x.AddCalendar(calName, It.Is <HolidayCalendar>( c => c.ExcludedDates.Contains(exclusionDate1) && c.ExcludedDates.Contains(exclusionDate2) && c.ExcludedDates.Count == 2), true, true), Times.Once); }
public override Builder set(string propertyName, object newValue) { switch (propertyName.GetHashCode()) { case 100346066: // index this.index_Renamed = (OvernightIndex)newValue; break; case 394230283: // fixingCalendar this.fixingCalendar_Renamed = (HolidayCalendar)newValue; break; case -2129778896: // startDate this.startDate_Renamed = (LocalDate)newValue; break; case -1607727319: // endDate this.endDate_Renamed = (LocalDate)newValue; break; case -92095804: // rateCutOffDays this.rateCutOffDays_Renamed = (int?)newValue.Value; break; default: throw new NoSuchElementException("Unknown property: " + propertyName); } return(this); }
/// <summary> /// Register new <see cref="HolidayCalendar"/> and optionally provide an initital set of dates to exclude. /// </summary> /// <param name="name"></param> /// <param name="description"></param> /// <param name="daysExcludedUtc"></param> public Guid AddHolidayCalendar(string name, string description, IList <DateTime> daysExcludedUtc = null) { var holidays = new HolidayCalendar { Description = description }; if (null != daysExcludedUtc && daysExcludedUtc.Count > 0) { foreach (var dateTime in daysExcludedUtc) { holidays.AddExcludedDate(dateTime); } } Guid id; using (var tran = new TransactionScope()) { id = _persistanceStore.UpsertCalendarIdMap(name); _scheduler.AddCalendar(name, holidays, true, true); tran.Complete(); } return(id); }
private static async Task ScheduleSayHelloJob(IScheduler scheduler) { //创建作业和触发器 var jobDetail = JobBuilder.Create <SayHelloJob>() .SetJobData(new JobDataMap() { new KeyValuePair <string, object>("UserName", "Tom"), new KeyValuePair <string, object>("RunSuccess", false) }) .WithIdentity("SayHelloJob-Tom", "DemoGroup") .RequestRecovery(true) .StoreDurably(true) .Build(); var calandar = new HolidayCalendar(); calandar.AddExcludedDate(DateTime.Today); await scheduler.AddCalendar("holidayCalendar", calandar, false, false); var trigger = TriggerBuilder.Create() .WithCronSchedule("*/1 * * * * ?") //.ModifiedByCalendar("holidayCalendar") .Build(); //添加调度 await scheduler.ScheduleJob(jobDetail, trigger); }
public void TestSqlServerStress() { NameValueCollection properties = new NameValueCollection(); properties["quartz.scheduler.instanceName"] = "TestScheduler"; properties["quartz.scheduler.instanceId"] = "instance_one"; properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz"; properties["quartz.threadPool.threadCount"] = "10"; properties["quartz.threadPool.threadPriority"] = "Normal"; properties["quartz.jobStore.misfireThreshold"] = "60000"; properties["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz"; properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.StdAdoDelegate, Quartz"; properties["quartz.jobStore.useProperties"] = "false"; properties["quartz.jobStore.dataSource"] = "default"; properties["quartz.jobStore.tablePrefix"] = "QRTZ_"; properties["quartz.jobStore.clustered"] = clustered.ToString(); properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz"; RunAdoJobStoreTest("SqlServer-20", "SQLServer", properties); properties["quartz.jobStore.lockHandler.type"] = "Quartz.Impl.AdoJobStore.UpdateLockRowSemaphore, Quartz"; string connectionString; if (!dbConnectionStrings.TryGetValue("SQLServer", out connectionString)) { throw new Exception("Unknown connection string id: " + "SQLServer"); } properties["quartz.dataSource.default.connectionString"] = connectionString; properties["quartz.dataSource.default.provider"] = "SqlServer-20"; // First we must get a reference to a scheduler ISchedulerFactory sf = new StdSchedulerFactory(properties); IScheduler sched = sf.GetScheduler(); try { CleanUp(sched); if (scheduleJobs) { ICalendar cronCalendar = new CronCalendar("0/5 * * * * ?"); ICalendar holidayCalendar = new HolidayCalendar(); for (int i = 0; i < 100000; ++i) { ITrigger trigger = new SimpleTriggerImpl("calendarsTrigger", "test", SimpleTriggerImpl.RepeatIndefinitely, TimeSpan.FromSeconds(1)); JobDetailImpl jd = new JobDetailImpl("testJob", "test", typeof(NoOpJob)); sched.ScheduleJob(jd, trigger); } } sched.Start(); Thread.Sleep(TimeSpan.FromSeconds(30)); } finally { sched.Shutdown(false); } }
/// <summary> /// Restricted copy constructor. </summary> /// <param name="beanToCopy"> the bean to copy from, not null </param> internal Builder(OvernightCompoundedRateComputation beanToCopy) { this.index_Renamed = beanToCopy.Index; this.fixingCalendar_Renamed = beanToCopy.FixingCalendar; this.startDate_Renamed = beanToCopy.StartDate; this.endDate_Renamed = beanToCopy.EndDate; this.rateCutOffDays_Renamed = beanToCopy.RateCutOffDays; }
public void SerializeHolidayCalendar() { var calendar = new HolidayCalendar(); calendar.Description = "description"; calendar.AddExcludedDate(DateTime.UtcNow.Date); CompareSerialization(calendar); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testImmutableReferenceDataWithMergedHolidays() public virtual void testImmutableReferenceDataWithMergedHolidays() { HolidayCalendar hc = HolidayCalendars.FRI_SAT.combinedWith(HolidayCalendars.SAT_SUN); ImmutableReferenceData referenceData = ImmutableReferenceData.of(hc.Id, hc); LocalDate date = BusinessDayAdjustment.of(BusinessDayConventions.PRECEDING, hc.Id).adjust(LocalDate.of(2016, 8, 20), referenceData); assertEquals(LocalDate.of(2016, 8, 18), date); }
public async Task TestSqlServerStress(string serializerType) { NameValueCollection properties = new NameValueCollection(); properties["quartz.scheduler.instanceName"] = "TestScheduler"; properties["quartz.scheduler.instanceId"] = "instance_one"; properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz"; properties["quartz.threadPool.threadCount"] = "10"; properties["quartz.serializer.type"] = TestConstants.DefaultSerializerType; properties["quartz.jobStore.misfireThreshold"] = "60000"; properties["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz"; properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.StdAdoDelegate, Quartz"; properties["quartz.jobStore.useProperties"] = "false"; properties["quartz.jobStore.dataSource"] = "default"; properties["quartz.jobStore.tablePrefix"] = "QRTZ_"; properties["quartz.jobStore.clustered"] = clustered.ToString(); properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz"; await RunAdoJobStoreTest(TestConstants.DefaultSqlServerProvider, "SQLServer", serializerType, properties); string connectionString; if (!dbConnectionStrings.TryGetValue("SQLServer", out connectionString)) { throw new Exception("Unknown connection string id: " + "SQLServer"); } properties["quartz.dataSource.default.connectionString"] = connectionString; properties["quartz.dataSource.default.provider"] = TestConstants.DefaultSqlServerProvider; // First we must get a reference to a scheduler ISchedulerFactory sf = new StdSchedulerFactory(properties); IScheduler sched = await sf.GetScheduler(); try { await sched.Clear(); if (scheduleJobs) { ICalendar cronCalendar = new CronCalendar("0/5 * * * * ?"); ICalendar holidayCalendar = new HolidayCalendar(); for (int i = 0; i < 100000; ++i) { ITrigger trigger = new SimpleTriggerImpl("calendarsTrigger", "test", SimpleTriggerImpl.RepeatIndefinitely, TimeSpan.FromSeconds(1)); JobDetailImpl jd = new JobDetailImpl("testJob", "test", typeof(NoOpJob)); await sched.ScheduleJob(jd, trigger); } } await sched.Start(); await Task.Delay(TimeSpan.FromSeconds(30)); } finally { await sched.Shutdown(false); } }
public virtual void test_nearest() { HolidayCalendar cal = ImmutableHolidayCalendar.of(HolidayCalendarId.of("Test"), ImmutableList.of(MON_2014_07_14), SATURDAY, SUNDAY); assertEquals(NEAREST.adjust(FRI_2014_07_11, cal), FRI_2014_07_11); assertEquals(NEAREST.adjust(SAT_2014_07_12, cal), FRI_2014_07_11); assertEquals(NEAREST.adjust(SUN_2014_07_13, cal), TUE_2014_07_15); assertEquals(NEAREST.adjust(MON_2014_07_14, cal), TUE_2014_07_15); }
public void TestHolidayCalendarSerialization() { HolidayCalendar holidayCalendar = new HolidayCalendar(); holidayCalendar.AddExcludedDate(new DateTime(2010, 1, 20)); HolidayCalendar clone = holidayCalendar.DeepClone(); Assert.AreEqual(1, clone.ExcludedDates.Count); }
//------------------------------------------------------------------------- public LocalDate calculateMaturityFromFixing(LocalDate fixingDate, ReferenceData refData) { // handle case where the input date is not a valid fixing date HolidayCalendar fixingCal = fixingCalendar.resolve(refData); LocalDate fixingBusinessDay = fixingCal.nextOrSame(fixingDate); // find the maturity date using the offset and calendar in DaysAdjustment return(maturityDateOffset.adjust(fixingBusinessDay, refData)); }