public void Fire() { scheduler.Start(); Parallel.ForEach(jobTypes, jobType => { AutoRunAttribute configuration = jobType.GetAttribute <AutoRunAttribute>(); if (configuration == null) { return; // sanity. } log.Debug(Resources.Debug.SchedulingAutoRunJob.FormatWith(jobType.Name)); if (configuration.RunOnce) { scheduler.StartJob(jobType); } else { DateTimeOffset now = DateTimeOffset.UtcNow; DateTimeOffset offset = now.AddMinutes(configuration.Delay); int minutes = configuration.Interval ?? AutoRunAttribute.DefaultInterval; IScheduleBuilder schedule = DailyTimeIntervalScheduleBuilder.Create().WithIntervalInMinutes(minutes); ITrigger trigger = TriggerBuilder.Create().StartAt(offset).WithSchedule(schedule).Build(); scheduler.ScheduleJob(jobType, trigger); } }); }
/// <summary> /// Produce the <see cref="ITrigger" />. /// </summary> /// <remarks> /// </remarks> /// <returns>a Trigger that meets the specifications of the builder.</returns> public ITrigger Build() { if (scheduleBuilder == null) { scheduleBuilder = SimpleScheduleBuilder.Create(); } IMutableTrigger trig = scheduleBuilder.Build(); trig.CalendarName = calendarName; trig.Description = description; trig.StartTimeUtc = startTime; trig.EndTimeUtc = endTime; if (key == null) { key = new TriggerKey(Guid.NewGuid().ToString(), null); } trig.Key = key; if (jobKey != null) { trig.JobKey = jobKey; } trig.Priority = priority; if (!jobDataMap.IsEmpty) { trig.JobDataMap = jobDataMap; } return(trig); }
/// <summary> /// //1.0 调度任务分两种,1-重复执行任务,间隔一段时间 2-每天的某一时刻执行一次 /// 2-每日执行一次 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name"></param> /// <param name="schebuilder"></param> /// <returns></returns> public async Task ScheduleJob_Once <T>(string name, IScheduleBuilder schebuilder) where T : IJob { try { //1.0 从调度工厂中获取一个调度对象 IScheduler scheduler = await factory.GetScheduler(); // 开启调度 await scheduler.Start(); //定义一个任务 IJobDetail job = JobBuilder.Create <T>() .WithIdentity(name + "job", name + "group") .Build(); //定义一个任务触发器,每10s执行一次 Trigger the job to run now, and then repeat every 10 seconds ITrigger trigger = TriggerBuilder.Create() .WithIdentity(name + "trigger", name + "group") .StartNow() .WithSchedule(schebuilder) .Build(); // 把任务和任务触发器一起给调度创建任务 await scheduler.ScheduleJob(job, trigger); } catch (SchedulerException se) { Console.WriteLine(se); } }
public void Restore(IScheduleBuilder builder) { this.Interval = this.GetField <TimeSpan>("interval", builder); this.NotifyOfPropertyChange(() => this.Interval); this.RepeatCount = this.GetField <int>("repeatCount", builder); this.NotifyOfPropertyChange(() => this.RepeatCount); }
/// <summary> /// Handles with a given text matches the Expression5 field. /// </summary> /// <param name="nameValueCollection">A collection of values from the named capture groups.</param> /// <param name="results">The results.</param> private void Expression5Handler(NameValueCollection nameValueCollection, TimeZoneInfo timeZone, TextToScheduleResults results) { var days = nameValueCollection.GetValues("DAY"); var months = nameValueCollection.GetValues("MONTH"); var timesToFire = nameValueCollection.GetValues("TIME"); var dayValues = days.Select(day => GrammarHelper.GetDayValue(day)) .Select(day => GetDayCronValue(day).ToList()); List <string> cronExpressions = new List <string>(); string cron_day = "*"; string cron_month = "*"; if (days != null) { var targetDays = days.Select(x => GrammarHelper.GetDayValue(x)); var targetDayCron = targetDays.Select(x => GetDayCronValue(x)); cron_day = string.Join(",", targetDayCron); } if (months != null) { var targetMonths = GrammarHelper.GetMonthValues(months); var targetMonthsCron = targetMonths.Select(x => GetMonthCronValue(x)); cron_month = string.Join(",", targetMonthsCron); } if (timesToFire == null) // if times are not specified assume midnight { timesToFire = new string[] { "00:00" } } ; foreach (var item in timesToFire) { var time = GrammarHelper.GetTimeFromTimeString(item).Value; string cron_sec = time.Second.ToString(); string cron_min = time.Minute.ToString(); string cron_hour = time.Hour.ToString(); string cronString = string.Format("{0} {1} {2} {3} {4} ?", cron_sec, cron_min, cron_hour, cron_day, cron_month); cronExpressions.Add(cronString); } foreach (var cron in cronExpressions) { var triggerBuilder = TriggerBuilder.Create(); IScheduleBuilder schedule = CreateScheduleWithCron(cron, timeZone); triggerBuilder.WithSchedule(schedule); results.Add(triggerBuilder); } }
public List<Installment> BuildTranche(IEnumerable<Installment> schedule, IScheduleBuilder scheduleBuilder, IScheduleConfiguration scheduleConfiguration, ITrancheConfiguration trancheConfiguration) { var rhc = (IScheduleConfiguration)scheduleConfiguration.Clone(); rhc.Amount = trancheConfiguration.Amount; rhc.NumberOfInstallments = trancheConfiguration.NumberOfInstallments; rhc.GracePeriod = trancheConfiguration.GracePeriod; rhc.InterestRate = trancheConfiguration.InterestRate; rhc.StartDate = trancheConfiguration.StartDate; rhc.PreferredFirstInstallmentDate = trancheConfiguration.PreferredFirstInstallmentDate; var lhc = (IScheduleConfiguration)rhc.Clone(); lhc.Amount = schedule.Sum(i => i.CapitalRepayment.Value - i.PaidCapital.Value); if (!trancheConfiguration.ApplyNewInterestRateToOlb) { lhc.InterestRate = scheduleConfiguration.InterestRate; } var lhs = scheduleBuilder.BuildSchedule(lhc); var rhs = scheduleBuilder.BuildSchedule(rhc); var result = new List<Installment>(); // Merge the two schedules var max = Math.Max(lhs.Count, rhs.Count); for (var i = 0; i < max; i++) { var lhi = i >= lhs.Count ? null : lhs[i]; var rhi = i >= rhs.Count ? null : rhs[i]; Installment installment; if (lhi == null) { installment = rhi; } else if (rhi == null) { installment = lhi; } else { installment = new Installment { Number = lhi.Number, StartDate = lhi.StartDate, ExpectedDate = lhi.ExpectedDate, //RepaymentDate = lhi.RepaymentDate, CapitalRepayment = lhi.CapitalRepayment + rhi.CapitalRepayment, InterestsRepayment = lhi.InterestsRepayment + rhi.InterestsRepayment, OLB = lhi.OLB + rhi.OLB, }; } result.Add(installment); } result[0].InterestsRepayment += GetExtraInterest(schedule, scheduleConfiguration, trancheConfiguration); return result; }
public Trainer(IWordStorage wordStorage, IStorage<WordResult> wordResultStorage, Language language, IWordSessionProvider wordSessionProvider, IScheduleBuilder scheduleBuilder, int penaltyRepetitionCount) { this.wordStorage = wordStorage; this.wordResultStorage = wordResultStorage; this.Language = language; this.wordSessionProvider = wordSessionProvider; this.scheduleBuilder = scheduleBuilder; this.penaltyRepetitionCount = penaltyRepetitionCount; }
public WalkingFacade(IDogPackBuilder dogPackBuilder, IScheduleBuilder walksBuilder, IDogWalkersRepository dogWalkersRepo, IRevenueCalcService revenueCalcService) { _dogPackBuilder = dogPackBuilder; _walksBuilder = walksBuilder; _dogWalkersRepo = dogWalkersRepo; _revenueCalcService = revenueCalcService; }
public void Restore(IScheduleBuilder builder) { var expr = this.GetField <CronExpression>("cronExpression", builder); if (expr != null) { this.Expression = expr.CronExpressionString; this.NotifyOfPropertyChange(() => this.Expression); } }
public TriggerPropertyBundle(IScheduleBuilder sb, string[]?statePropertyNames, object[]?statePropertyValues) { ScheduleBuilder = sb; StatePropertyNames = statePropertyNames ?? Array.Empty <string>(); StatePropertyValues = statePropertyValues ?? Array.Empty <object>(); if (StatePropertyNames.Length != StatePropertyValues.Length) { throw new ArgumentException("property names and values must be of same length"); } }
void CreateJob(Type jobType, IScheduleBuilder scheduleBuider, IScheduler scheduler) { IJobDetail job = JobBuilder.Create(jobType) .Build(); var trigger = TriggerBuilder.Create() .StartNow(); if (scheduleBuider != null) trigger.WithSchedule(scheduleBuider); scheduler.ScheduleJob(job, trigger.Build()); }
public T GetField <T>(string fieldName, IScheduleBuilder builder) { var field = typeof(CronScheduleBuilder).GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance); if (field != null) { return((T)field.GetValue(builder)); } else { return(default(T)); } }
void CreateJob(Type jobType, IScheduleBuilder scheduleBuider, IScheduler scheduler) { IJobDetail job = JobBuilder.Create(jobType) .Build(); var trigger = TriggerBuilder.Create() .StartNow(); if (scheduleBuider != null) { trigger.WithSchedule(scheduleBuider); } scheduler.ScheduleJob(job, trigger.Build()); }
public void FlatSchedule_Setup() { _configuration = new ScheduleConfiguration { NumberOfInstallments = 5, Amount = 5000, InterestRate = 24m, StartDate = new DateTime(2013, 1, 1), PreferredFirstInstallmentDate = new DateTime(2013, 2, 1), PeriodPolicy = new Monthly30DayPeriodPolicy(), YearPolicy = new ThreeHundredSixtyDayYearPolicy(), RoundingPolicy = new TwoDecimalRoundingPolicy(), CalculationPolicy = new FlatInstallmentCalculationPolicy(), AdjustmentPolicy = new LastInstallmentAdjustmentPolicy(), DateShiftPolicy = new NoDateShiftPolicy(), }; _builder = new ScheduleBuilder(); }
public void AnnuitySchedule_Setup() { _configuration = new ScheduleConfiguration { NumberOfInstallments = 12, Amount = 100000, InterestRate = 36m, StartDate = new DateTime(2013, 12, 10), PreferredFirstInstallmentDate = new DateTime(2014, 1, 10), PeriodPolicy = new MonthlyPeriodPolicy(), YearPolicy = new ThreeHundredSixtyDayYearPolicy(), RoundingPolicy = new IntegerRoundingPolicy(), CalculationPolicy = new AnnuityInstallmentCalculationPolicy(), AdjustmentPolicy = new LastInstallmentAdjustmentPolicy(), DateShiftPolicy = new NoDateShiftPolicy(), }; _builder = new ScheduleBuilder(); }
public async void AddWeeklyJob <T>(string name, string group) where T : IJob { IJobDetail job = JobBuilder.Create <T>() .WithIdentity(name, group) .Build(); IScheduleBuilder scheduleBuilder = CronScheduleBuilder .CronSchedule(" 0 0 3 ? * SUN *") // EVERY SUNDAY AT 03:00 AM .InTimeZone(TimeZoneInfo.Utc); ITrigger jobTrigger = TriggerBuilder.Create() .WithIdentity(name + "Trigger", group) .WithSchedule(scheduleBuilder) .StartNow() .Build(); await Scheduler.ScheduleJob(job, jobTrigger); }
public void BuildEngine_Setup() { _configuration = new ScheduleConfiguration { Amount = 10000, GracePeriod = 0, InterestRate = 0.24m, NumberOfInstallments = 5, StartDate = new DateTime(2013, 1, 1), PreferredFirstInstallmentDate = new DateTime(2013, 2, 5), ChargeInterestDuringGracePeriod = true, PeriodPolicy = new MonthlyPeriodPolicy(), YearPolicy = new ActualNumberOfDayYearPolicy(), RoundingPolicy = new TwoDecimalRoundingPolicy(), CalculationPolicy = new FlatInstallmentCalculationPolicy(), AdjustmentPolicy = new LastInstallmentAdjustmentPolicy(), DateShiftPolicy = new NoDateShiftPolicy(), }; _builder = new ScheduleBuilder(); }
/// <summary> /// Set the <see cref="IScheduleBuilder" /> that will be used to define the /// Trigger's schedule. /// </summary> /// <remarks> /// <para>The particular <see cref="IScheduleBuilder" /> used will dictate /// the concrete type of Trigger that is produced by the TriggerBuilder.</para> /// </remarks> /// <param name="scheduleBuilder">the SchedulerBuilder to use.</param> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="IScheduleBuilder" /> /// <seealso cref="SimpleScheduleBuilder" /> /// <seealso cref="CronScheduleBuilder" /> /// <seealso cref="CalendarIntervalScheduleBuilder" /> public TriggerBuilder WithSchedule(IScheduleBuilder scheduleBuilder) { this.scheduleBuilder = scheduleBuilder; return(this); }
public TriggerPropertyBundle(IScheduleBuilder sb, string[] statePropertyNames, object[] statePropertyValues) { this.sb = sb; this.statePropertyNames = statePropertyNames; this.statePropertyValues = statePropertyValues; }
/// <summary> /// Handles with a given text matches the Expression2 field. /// </summary> /// <param name="nameValueCollection">A collection of values from the named capture groups.</param> /// <param name="results">The results.</param> private void Expression2Handler(NameValueCollection nameValueCollection, TimeZoneInfo timeZone, TextToScheduleResults results) { var timesToFire = nameValueCollection.GetValues("TIME"); var dayOfWeekSpecs = nameValueCollection.GetValues("DAYOFWEEK"); var monthSpecs = nameValueCollection.GetValues("MONTH"); var ordinals = nameValueCollection.GetValues("ORDINAL"); //init cron values List <string> cronExpressions = new List <string>(); if (timesToFire == null) // if times are not specified assume midnight { timesToFire = new string[] { "00:00" } } ; foreach (var time in timesToFire) { DateTime date = DateTime.Today; //default date to today if (time != null) { date = GrammarHelper.GetTimeFromTimeString(time).Value; } string cron_sec = date.Second.ToString(); string cron_min = date.Minute.ToString(); string cron_hour = date.Hour.ToString(); string cron_day = "?"; string cron_month = "*"; string cron_dayofWeek = "*"; if (monthSpecs != null) { var months = GrammarHelper.GetMonthValues(monthSpecs); cron_month = string.Join(",", months.Select(mon => GetMonthCronValue(mon))); } if (dayOfWeekSpecs != null) { var dows = GrammarHelper.GetDayOfWeekValues(dayOfWeekSpecs); cron_dayofWeek = string.Join(",", dows.Select(x => GetDayOfWeekCronValue(x))); } if (ordinals != null) { if (dayOfWeekSpecs != null) { //combine ordinals and dayOfWeeks var combined = from a in GrammarHelper.GetOrdinalValues(ordinals) from b in GrammarHelper.GetDayOfWeekValues(dayOfWeekSpecs) select new { Ordinal = a, DayOfWeek = b }; foreach (var item in combined) { cron_dayofWeek = GetDayOfWeekCronValue(item.DayOfWeek); cron_dayofWeek += GetOrdinalCronValue(item.Ordinal); string cronString = string.Format(string.Join(" ", new string[] { cron_sec, cron_min, cron_hour, cron_day, cron_month, cron_dayofWeek })); cronExpressions.Add(cronString); } } if (dayOfWeekSpecs == null) //"day" was specified as DOW, handle special case { //handle special cases cron_dayofWeek = "?"; foreach (var o in GrammarHelper.GetOrdinalValues(ordinals)) { cron_day = GetOrdinalCronValue(o).Replace("#", ""); string cronString = string.Format(string.Join(" ", new string[] { cron_sec, cron_min, cron_hour, cron_day, cron_month, cron_dayofWeek })); cronExpressions.Add(cronString); } } } else //no ordinal was specified { string cronString = string.Format(string.Join(" ", new string[] { cron_sec, cron_min, cron_hour, cron_day, cron_month, cron_dayofWeek })); cronExpressions.Add(cronString); } } foreach (var cron in cronExpressions) { var triggerBuilder = TriggerBuilder.Create(); IScheduleBuilder schedule = CreateScheduleWithCron(cron, timeZone); triggerBuilder.WithSchedule(schedule); results.Add(triggerBuilder); } }
public IEnumerable<IInstallment> AssembleRescheduling( IEnumerable<IInstallment> schedule, IScheduleConfiguration scheduleConfiguration, IScheduleConfiguration rescheduleConfiguration, IScheduleBuilder scheduleBuilder, decimal currentOlb) { // Build a new combined schedule // 1. To close all active installments before date of rescheduling. // Get the part of the schedule that comes before the rescheduling date... var newSchedule = from installment in schedule where installment.RepaymentDate <= rescheduleConfiguration.StartDate select installment; // Get overpaid principal = sum of paid principal after the rescheduling date... var overpaidPrincipal = ( from installment in schedule where installment.RepaymentDate > rescheduleConfiguration.StartDate select installment ).Sum(installment => installment.PaidPrincipal); //Add overpaid principal to paid principal of the last installment before the rescheduling if (newSchedule.Any()) newSchedule.Last().PaidPrincipal += overpaidPrincipal; // Close all active installments before date of rescheduling var olbDifference = 0m; foreach (var installment in newSchedule) { installment.Olb += olbDifference; olbDifference += installment.Principal - installment.PaidPrincipal; installment.Principal = installment.PaidPrincipal; installment.Interest = installment.PaidInterest; } // 2. To store amounts of interest paid, those for installments after date of rescheduling. var overpaidInterest = ( from installment in schedule where installment.RepaymentDate > rescheduleConfiguration.StartDate select installment ).Sum(installment => installment.PaidInterest); // 3. To get total of first calculated interest. It will be interest between last closed installment and date of rescheduling // plus interest between date of rescheduling and first repayment date // To calculate extra interest for used days. // For the case when date of rescheduling < date of first installment var usedDays = 0; if (newSchedule.Any()) { usedDays = (rescheduleConfiguration.StartDate - newSchedule.Last().EndDate).Days; } var daysInYear = scheduleConfiguration.YearPolicy.GetNumberOfDays(rescheduleConfiguration.StartDate); var extraInterest = currentOlb*scheduleConfiguration.InterestRate/100*usedDays/daysInYear; // To calculate interest between date of rescheduling and first repayment date. var daysTillRepayment = (rescheduleConfiguration.PreferredFirstInstallmentDate - rescheduleConfiguration.StartDate).Days; decimal firstInterest = 0; if (rescheduleConfiguration.GracePeriod == 0 || rescheduleConfiguration.ChargeInterestDuringGracePeriod) firstInterest = currentOlb*rescheduleConfiguration.InterestRate/100*daysTillRepayment/daysInYear; // 4. We generate new schedule according to new parametrs. rescheduleConfiguration.Amount = currentOlb; rescheduleConfiguration.AdjustmentPolicy = scheduleConfiguration.AdjustmentPolicy; rescheduleConfiguration.CalculationPolicy = scheduleConfiguration.CalculationPolicy; rescheduleConfiguration.DateShiftPolicy = scheduleConfiguration.DateShiftPolicy; rescheduleConfiguration.PeriodPolicy = scheduleConfiguration.PeriodPolicy; rescheduleConfiguration.RoundingPolicy = scheduleConfiguration.RoundingPolicy; rescheduleConfiguration.YearPolicy = scheduleConfiguration.YearPolicy; var rescheduled = scheduleBuilder.BuildSchedule(rescheduleConfiguration); // Adjust the new schedule's installment numbers var increment = newSchedule.Count(); foreach (var installment in rescheduled) { installment.Number += increment; } // Distribute the extra and overpaid interest if (rescheduleConfiguration.GracePeriod > 0 && !rescheduleConfiguration.ChargeInterestDuringGracePeriod) rescheduled[rescheduleConfiguration.GracePeriod].Interest += rescheduleConfiguration.RoundingPolicy.Round(extraInterest); else rescheduled.First().Interest = rescheduleConfiguration.RoundingPolicy.Round(firstInterest + extraInterest); foreach (var installment in rescheduled) { if (installment.Interest < overpaidInterest) { installment.PaidInterest = installment.Interest; overpaidInterest -= installment.Interest; } else { installment.PaidInterest = overpaidInterest; break; } } var result = new List<IInstallment>(); result.AddRange(newSchedule); result.AddRange(rescheduled); return result; }
/// <summary> /// Handles with a given text matches the Expression3 field. /// </summary> /// <param name="nameValueCollection">A collection of values from the named capture groups.</param> /// <param name="results">The results.</param> private void Expression3Handler(NameValueCollection nameValueCollection, TimeZoneInfo timeZone, TextToScheduleResults results) { var timesToFire = nameValueCollection.GetValues("TIME"); var dateSpec = nameValueCollection["DATESPEC"]; var monthString = nameValueCollection["MONTH"]; var dayString = nameValueCollection["DAY"]; var yearString = nameValueCollection["YEAR"]; //init cron values List <string> cronExpressions = new List <string>(); if (timesToFire == null) // if times are not specified assume midnight { timesToFire = new string[] { "00:00" } } ; foreach (var time in timesToFire) { DateTime date = DateTime.Today; //default date to today if (time != null) { date = GrammarHelper.GetTimeFromTimeString(time).Value; } string cron_sec = date.Second.ToString(); string cron_min = date.Minute.ToString(); string cron_hour = date.Hour.ToString(); string cron_day = "*"; string cron_month = "*"; string cron_dayofWeek = "?"; string cron_year = null; cron_month = GetMonthCronValue(GrammarHelper.GetMonthValue(monthString)); if (dayString != null) { cron_day = GetDayCronValue(GrammarHelper.GetDayValue(dayString)); } else { cron_day = GetDayCronValue(1); } if (yearString != null) { cron_year = GetYearCronValue(GrammarHelper.GetYearValue(yearString)); } //build cron string string cronString = null; if (cron_year != null) { cronString = string.Format(string.Join(" ", new string[] { cron_sec, cron_min, cron_hour, cron_day, cron_month, cron_dayofWeek, cron_year })); } else { cronString = string.Format(string.Join(" ", new string[] { cron_sec, cron_min, cron_hour, cron_day, cron_month, cron_dayofWeek })); } //add cron string cronExpressions.Add(cronString); } foreach (var cron in cronExpressions) { var triggerBuilder = TriggerBuilder.Create(); IScheduleBuilder schedule = CreateScheduleWithCron(cron, timeZone); triggerBuilder.WithSchedule(schedule); results.Add(triggerBuilder); } }
public Trainer4Test(IWordStorage wordStorage, IStorage<WordResult> wordResultStorage, Language language, IWordSessionProvider wordSessionProvider, IScheduleBuilder scheduleBuilder) : base(wordStorage, wordResultStorage, language, wordSessionProvider, scheduleBuilder, 1) { }
public IEnumerable <Installment> AssembleTranche( IEnumerable <Installment> schedule, IScheduleConfiguration scheduleConfiguration, ITrancheConfiguration trancheConfiguration, IScheduleBuilder scheduleBuilder, ITrancheBuilder trancheBuilder) { // Build a new combined schedule var trancheSchedule = trancheBuilder.BuildTranche(schedule, scheduleBuilder, scheduleConfiguration, trancheConfiguration); // Get an interested paid in advance, whereas "in advance" means after the new tranche date var overpaidInterest = ( from installment in schedule where installment.ExpectedDate > trancheConfiguration.StartDate select installment ).Sum(installment => installment.PaidInterests.Value); // Get the part of the schedule that comes before the tranche date... var newSchedule = from installment in schedule where installment.ExpectedDate <= trancheConfiguration.StartDate select installment; // ...and force close it (set expected equal to paid) var olbDifference = 0m; foreach (var installment in newSchedule) { installment.OLB += olbDifference; olbDifference += installment.CapitalRepayment.Value - installment.PaidCapital.Value; if (!(installment.CapitalRepayment == installment.PaidCapital && installment.InterestsRepayment == installment.PaidInterests)) { installment.PaidDate = trancheConfiguration.StartDate; } installment.CapitalRepayment = installment.PaidCapital; installment.InterestsRepayment = installment.PaidInterests; } // Adjust the new schedule's installment numbers var increment = newSchedule.Count(); foreach (var installment in trancheSchedule) { installment.Number += increment; } var result = new List <Installment>(); result.AddRange(newSchedule); // Distribute the overpaid interest foreach (var installment in trancheSchedule) { if (installment.InterestsRepayment < overpaidInterest) { installment.PaidInterests = installment.InterestsRepayment; overpaidInterest -= installment.InterestsRepayment.Value; } else { installment.PaidInterests = overpaidInterest; break; } } result.AddRange(trancheSchedule); return(result); }
public ITriggerConfigurator WithSchedule(IScheduleBuilder scheduleBuilder) { triggerBuilder.WithSchedule(scheduleBuilder); return(this); }
public IEnumerable <IInstallment> AssembleRescheduling( IEnumerable <IInstallment> schedule, IScheduleConfiguration scheduleConfiguration, IScheduleConfiguration rescheduleConfiguration, IScheduleBuilder scheduleBuilder, decimal currentOlb) { // Build a new combined schedule // 1. To close all active installments before date of rescheduling. // Get the part of the schedule that comes before the rescheduling date... var newSchedule = from installment in schedule where installment.RepaymentDate <= rescheduleConfiguration.StartDate select installment; // Get overpaid principal = sum of paid principal after the rescheduling date... var overpaidPrincipal = ( from installment in schedule where installment.RepaymentDate > rescheduleConfiguration.StartDate select installment ).Sum(installment => installment.PaidPrincipal); //Add overpaid principal to paid principal of the last installment before the rescheduling if (newSchedule.Any()) { newSchedule.Last().PaidPrincipal += overpaidPrincipal; } // Close all active installments before date of rescheduling var olbDifference = 0m; foreach (var installment in newSchedule) { installment.Olb += olbDifference; olbDifference += installment.Principal - installment.PaidPrincipal; installment.Principal = installment.PaidPrincipal; installment.Interest = installment.PaidInterest; } // 2. To store amounts of interest paid, those for installments after date of rescheduling. var overpaidInterest = ( from installment in schedule where installment.RepaymentDate > rescheduleConfiguration.StartDate select installment ).Sum(installment => installment.PaidInterest); // 3. To get total of first calculated interest. It will be interest between last closed installment and date of rescheduling // plus interest between date of rescheduling and first repayment date // To calculate extra interest for used days. // For the case when date of rescheduling < date of first installment var usedDays = 0; if (newSchedule.Any()) { usedDays = (rescheduleConfiguration.StartDate - newSchedule.Last().EndDate).Days; } var daysInYear = scheduleConfiguration.YearPolicy.GetNumberOfDays(rescheduleConfiguration.StartDate); var extraInterest = currentOlb * scheduleConfiguration.InterestRate / 100 * usedDays / daysInYear; // To calculate interest between date of rescheduling and first repayment date. var daysTillRepayment = (rescheduleConfiguration.PreferredFirstInstallmentDate - rescheduleConfiguration.StartDate).Days; decimal firstInterest = 0; if (rescheduleConfiguration.GracePeriod == 0 || rescheduleConfiguration.ChargeInterestDuringGracePeriod) { firstInterest = currentOlb * rescheduleConfiguration.InterestRate / 100 * daysTillRepayment / daysInYear; } // 4. We generate new schedule according to new parametrs. rescheduleConfiguration.Amount = currentOlb; rescheduleConfiguration.AdjustmentPolicy = scheduleConfiguration.AdjustmentPolicy; rescheduleConfiguration.CalculationPolicy = scheduleConfiguration.CalculationPolicy; rescheduleConfiguration.DateShiftPolicy = scheduleConfiguration.DateShiftPolicy; rescheduleConfiguration.PeriodPolicy = scheduleConfiguration.PeriodPolicy; rescheduleConfiguration.RoundingPolicy = scheduleConfiguration.RoundingPolicy; rescheduleConfiguration.YearPolicy = scheduleConfiguration.YearPolicy; var rescheduled = scheduleBuilder.BuildSchedule(rescheduleConfiguration); // Adjust the new schedule's installment numbers var increment = newSchedule.Count(); foreach (var installment in rescheduled) { installment.Number += increment; } // Distribute the extra and overpaid interest if (rescheduleConfiguration.GracePeriod > 0 && !rescheduleConfiguration.ChargeInterestDuringGracePeriod) { rescheduled[rescheduleConfiguration.GracePeriod].Interest += rescheduleConfiguration.RoundingPolicy.Round(extraInterest); } else { rescheduled.First().Interest = rescheduleConfiguration.RoundingPolicy.Round(firstInterest + extraInterest); } foreach (var installment in rescheduled) { if (installment.Interest < overpaidInterest) { installment.PaidInterest = installment.Interest; overpaidInterest -= installment.Interest; } else { installment.PaidInterest = overpaidInterest; break; } } var result = new List <IInstallment>(); result.AddRange(newSchedule); result.AddRange(rescheduled); return(result); }
public IEnumerable<IInstallment> AssembleTranche( IEnumerable<IInstallment> schedule, IScheduleConfiguration scheduleConfiguration, ITrancheConfiguration trancheConfiguration, IScheduleBuilder scheduleBuilder, ITrancheBuilder trancheBuilder) { // Build a new combined schedule var trancheSchedule = trancheBuilder.BuildTranche(schedule, scheduleBuilder, scheduleConfiguration, trancheConfiguration); // Get an interested paid in advance, whereas "in advance" means after the new tranche date var overpaidInterest = ( from installment in schedule where installment.RepaymentDate > trancheConfiguration.StartDate select installment ).Sum(installment => installment.PaidInterest); // Get the part of the schedule that comes before the tranche date... var newSchedule = from installment in schedule where installment.RepaymentDate <= trancheConfiguration.StartDate select installment; // ...and force close it (set expected equal to paid) var olbDifference = 0m; foreach (var installment in newSchedule) { installment.Olb += olbDifference; olbDifference += installment.Principal - installment.PaidPrincipal; if (!(installment.Principal == installment.PaidPrincipal && installment.Interest == installment.PaidInterest)) { installment.LastPaymentDate = trancheConfiguration.StartDate; } installment.Principal = installment.PaidPrincipal; installment.Interest = installment.PaidInterest; } // Adjust the new schedule's installment numbers var increment = newSchedule.Count(); foreach (var installment in trancheSchedule) { installment.Number += increment; } var result = new List<IInstallment>(); result.AddRange(newSchedule); // Distribute the overpaid interest foreach (var installment in trancheSchedule) { if (installment.Interest < overpaidInterest) { installment.PaidInterest = installment.Interest; overpaidInterest -= installment.Interest; } else { installment.PaidInterest = overpaidInterest; break; } } result.AddRange(trancheSchedule); return result; }
/// <summary> /// Produce the <see cref="ITrigger" />. /// </summary> /// <remarks> /// </remarks> /// <returns>a Trigger that meets the specifications of the builder.</returns> public ITrigger Build() { if (scheduleBuilder == null) { scheduleBuilder = SimpleScheduleBuilder.Create(); } IMutableTrigger trig = scheduleBuilder.Build(); trig.CalendarName = calendarName; trig.Description = description; trig.StartTimeUtc = startTime; trig.EndTimeUtc = endTime; if (key == null) { key = new TriggerKey(Guid.NewGuid().ToString(), null); } trig.Key = key; if (jobKey != null) { trig.JobKey = jobKey; } trig.Priority = priority; if (!jobDataMap.IsEmpty) { trig.JobDataMap = jobDataMap; } return trig; }
public List <Installment> BuildTranche(IEnumerable <Installment> schedule, IScheduleBuilder scheduleBuilder, IScheduleConfiguration scheduleConfiguration, ITrancheConfiguration trancheConfiguration) { var rhc = (IScheduleConfiguration)scheduleConfiguration.Clone(); rhc.Amount = trancheConfiguration.Amount; rhc.NumberOfInstallments = trancheConfiguration.NumberOfInstallments; rhc.GracePeriod = trancheConfiguration.GracePeriod; rhc.InterestRate = trancheConfiguration.InterestRate; rhc.StartDate = trancheConfiguration.StartDate; rhc.PreferredFirstInstallmentDate = trancheConfiguration.PreferredFirstInstallmentDate; var lhc = (IScheduleConfiguration)rhc.Clone(); lhc.Amount = schedule.Sum(i => i.CapitalRepayment.Value - i.PaidCapital.Value); if (!trancheConfiguration.ApplyNewInterestRateToOlb) { lhc.InterestRate = scheduleConfiguration.InterestRate; } var lhs = scheduleBuilder.BuildSchedule(lhc); var rhs = scheduleBuilder.BuildSchedule(rhc); var result = new List <Installment>(); // Merge the two schedules var max = Math.Max(lhs.Count, rhs.Count); for (var i = 0; i < max; i++) { var lhi = i >= lhs.Count ? null : lhs[i]; var rhi = i >= rhs.Count ? null : rhs[i]; Installment installment; if (lhi == null) { installment = rhi; } else if (rhi == null) { installment = lhi; } else { installment = new Installment { Number = lhi.Number, StartDate = lhi.StartDate, ExpectedDate = lhi.ExpectedDate, //RepaymentDate = lhi.RepaymentDate, CapitalRepayment = lhi.CapitalRepayment + rhi.CapitalRepayment, InterestsRepayment = lhi.InterestsRepayment + rhi.InterestsRepayment, OLB = lhi.OLB + rhi.OLB, }; } result.Add(installment); } result[0].InterestsRepayment += GetExtraInterest(schedule, scheduleConfiguration, trancheConfiguration); return(result); }
public TriggerPropertyBundle(IScheduleBuilder sb) : this(sb, Array.Empty <string>(), Array.Empty <object>()) { }
protected virtual void ProcessInternal(string xml) { PrepForProcessing(); ValidateXml(xml); MaybeThrowValidationException(); // deserialize as object model XmlSerializer xs = new XmlSerializer(typeof(QuartzXmlConfiguration20)); QuartzXmlConfiguration20 data = (QuartzXmlConfiguration20)xs.Deserialize(new StringReader(xml)); if (data == null) { throw new SchedulerConfigException("Job definition data from XML was null after deserialization"); } // // Extract pre-processing commands // if (data.preprocessingcommands != null) { foreach (preprocessingcommandsType command in data.preprocessingcommands) { if (command.deletejobsingroup != null) { foreach (string s in command.deletejobsingroup) { string deleteJobGroup = s.NullSafeTrim(); if (!String.IsNullOrEmpty(deleteJobGroup)) { jobGroupsToDelete.Add(deleteJobGroup); } } } if (command.deletetriggersingroup != null) { foreach (string s in command.deletetriggersingroup) { string deleteTriggerGroup = s.NullSafeTrim(); if (!String.IsNullOrEmpty(deleteTriggerGroup)) { triggerGroupsToDelete.Add(deleteTriggerGroup); } } } if (command.deletejob != null) { foreach (preprocessingcommandsTypeDeletejob s in command.deletejob) { string name = s.name.TrimEmptyToNull(); string group = s.group.TrimEmptyToNull(); if (name == null) { throw new SchedulerConfigException("Encountered a 'delete-job' command without a name specified."); } jobsToDelete.Add(new JobKey(name, group)); } } if (command.deletetrigger != null) { foreach (preprocessingcommandsTypeDeletetrigger s in command.deletetrigger) { string name = s.name.TrimEmptyToNull(); string group = s.group.TrimEmptyToNull(); if (name == null) { throw new SchedulerConfigException("Encountered a 'delete-trigger' command without a name specified."); } triggersToDelete.Add(new TriggerKey(name, group)); } } } } log.Debug("Found " + jobGroupsToDelete.Count + " delete job group commands."); log.Debug("Found " + triggerGroupsToDelete.Count + " delete trigger group commands."); log.Debug("Found " + jobsToDelete.Count + " delete job commands."); log.Debug("Found " + triggersToDelete.Count + " delete trigger commands."); // // Extract directives // if (data.processingdirectives != null && data.processingdirectives.Length > 0) { bool overWrite = data.processingdirectives[0].overwriteexistingdata; log.Debug("Directive 'overwrite-existing-data' specified as: " + overWrite); OverWriteExistingData = overWrite; } else { log.Debug("Directive 'ignore-duplicates' not specified, defaulting to " + OverWriteExistingData); } if (data.processingdirectives != null && data.processingdirectives.Length > 0) { bool ignoreduplicates = data.processingdirectives[0].ignoreduplicates; log.Debug("Directive 'ignore-duplicates' specified as: " + ignoreduplicates); IgnoreDuplicates = ignoreduplicates; } else { log.Debug("Directive 'overwrite-existing-data' not specified, defaulting to " + IgnoreDuplicates); } // // Extract Job definitions... // List <jobdetailType> jobNodes = new List <jobdetailType>(); if (data.schedule != null && data.schedule.Length > 0 && data.schedule[0].job != null) { jobNodes.AddRange(data.schedule[0].job); } log.Debug("Found " + jobNodes.Count + " job definitions."); foreach (jobdetailType jobDetailType in jobNodes) { string jobName = jobDetailType.name.TrimEmptyToNull(); string jobGroup = jobDetailType.group.TrimEmptyToNull(); string jobDescription = jobDetailType.description.TrimEmptyToNull(); string jobTypeName = jobDetailType.jobtype.TrimEmptyToNull(); bool jobDurability = jobDetailType.durable; bool jobRecoveryRequested = jobDetailType.recover; Type jobType = typeLoadHelper.LoadType(jobTypeName); IJobDetail jobDetail = JobBuilder.NewJob(jobType) .WithIdentity(jobName, jobGroup) .WithDescription(jobDescription) .StoreDurably(jobDurability) .RequestRecovery(jobRecoveryRequested) .Build(); if (jobDetailType.jobdatamap != null && jobDetailType.jobdatamap.entry != null) { foreach (entryType entry in jobDetailType.jobdatamap.entry) { string key = entry.key.TrimEmptyToNull(); string value = entry.value.TrimEmptyToNull(); jobDetail.JobDataMap.Add(key, value); } } if (log.IsDebugEnabled) { log.Debug("Parsed job definition: " + jobDetail); } AddJobToSchedule(jobDetail); } // // Extract Trigger definitions... // List <triggerType> triggerEntries = new List <triggerType>(); if (data.schedule != null && data.schedule.Length > 0 && data.schedule[0].trigger != null) { triggerEntries.AddRange(data.schedule[0].trigger); } log.Debug("Found " + triggerEntries.Count + " trigger definitions."); foreach (triggerType triggerNode in triggerEntries) { string triggerName = triggerNode.Item.name.TrimEmptyToNull(); string triggerGroup = triggerNode.Item.group.TrimEmptyToNull(); string triggerDescription = triggerNode.Item.description.TrimEmptyToNull(); string triggerMisfireInstructionConst; string triggerCalendarRef = triggerNode.Item.calendarname.TrimEmptyToNull(); string triggerJobName = triggerNode.Item.jobname.TrimEmptyToNull(); string triggerJobGroup = triggerNode.Item.jobgroup.TrimEmptyToNull(); int triggerPriority = TriggerConstants.DefaultPriority; if (!triggerNode.Item.priority.IsNullOrWhiteSpace()) { triggerPriority = Convert.ToInt32(triggerNode.Item.priority); } DateTimeOffset triggerStartTime = SystemTime.UtcNow(); if (triggerNode.Item.Item != null) { if (triggerNode.Item.Item is DateTime) { triggerStartTime = new DateTimeOffset((DateTime)triggerNode.Item.Item); } else { triggerStartTime = triggerStartTime.AddSeconds(Convert.ToInt32(triggerNode.Item.Item)); } } DateTime?triggerEndTime = triggerNode.Item.endtimeSpecified ? triggerNode.Item.endtime : (DateTime?)null; TriggerKey triggerKey = new TriggerKey(triggerName, triggerGroup); IScheduleBuilder sched = null; if (triggerNode.Item is simpleTriggerType) { simpleTriggerType simpleTrigger = (simpleTriggerType)triggerNode.Item; triggerMisfireInstructionConst = simpleTrigger.misfireinstruction; string repeatCountString = simpleTrigger.repeatcount.TrimEmptyToNull(); string repeatIntervalString = simpleTrigger.repeatinterval.TrimEmptyToNull(); int repeatCount = ParseSimpleTriggerRepeatCount(repeatCountString); TimeSpan repeatInterval = repeatIntervalString == null ? TimeSpan.Zero : TimeSpan.FromMilliseconds(Convert.ToInt64(repeatIntervalString)); sched = SimpleScheduleBuilder.Create() .WithInterval(repeatInterval) .WithRepeatCount(repeatCount); if (!simpleTrigger.misfireinstruction.IsNullOrWhiteSpace()) { ((SimpleScheduleBuilder)sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(simpleTrigger.misfireinstruction)); } } else if (triggerNode.Item is cronTriggerType) { cronTriggerType cronTrigger = (cronTriggerType)triggerNode.Item; triggerMisfireInstructionConst = cronTrigger.misfireinstruction; string cronExpression = cronTrigger.cronexpression.TrimEmptyToNull(); string timezoneString = cronTrigger.timezone.TrimEmptyToNull(); TimeZoneInfo tz = timezoneString != null?TimeZoneInfo.FindSystemTimeZoneById(timezoneString) : null; sched = CronScheduleBuilder.CronSchedule(cronExpression) .InTimeZone(tz); if (!cronTrigger.misfireinstruction.IsNullOrWhiteSpace()) { ((CronScheduleBuilder)sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(cronTrigger.misfireinstruction)); } } else if (triggerNode.Item is calendarIntervalTriggerType) { calendarIntervalTriggerType calendarIntervalTrigger = (calendarIntervalTriggerType)triggerNode.Item; string repeatIntervalString = calendarIntervalTrigger.repeatinterval.TrimEmptyToNull(); triggerMisfireInstructionConst = calendarIntervalTrigger.misfireinstruction; IntervalUnit intervalUnit = ParseDateIntervalTriggerIntervalUnit(calendarIntervalTrigger.repeatintervalunit.TrimEmptyToNull()); int repeatInterval = repeatIntervalString == null ? 0 : Convert.ToInt32(repeatIntervalString); sched = CalendarIntervalScheduleBuilder.Create() .WithInterval(repeatInterval, intervalUnit); if (!calendarIntervalTrigger.misfireinstruction.IsNullOrWhiteSpace()) { ((CalendarIntervalScheduleBuilder)sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(calendarIntervalTrigger.misfireinstruction)); } } else { throw new SchedulerConfigException("Unknown trigger type in XML configuration"); } IMutableTrigger trigger = (IMutableTrigger)TriggerBuilder.Create() .WithIdentity(triggerName, triggerGroup) .WithDescription(triggerDescription) .ForJob(triggerJobName, triggerJobGroup) .StartAt(triggerStartTime) .EndAt(triggerEndTime) .WithPriority(triggerPriority) .ModifiedByCalendar(triggerCalendarRef) .WithSchedule(sched) .Build(); if (triggerNode.Item.jobdatamap != null && triggerNode.Item.jobdatamap.entry != null) { foreach (entryType entry in triggerNode.Item.jobdatamap.entry) { string key = entry.key.TrimEmptyToNull(); string value = entry.value.TrimEmptyToNull(); trigger.JobDataMap.Add(key, value); } } if (log.IsDebugEnabled) { log.Debug("Parsed trigger definition: " + trigger); } AddTriggerToSchedule(trigger); } }
/// <summary> /// Set the <see cref="IScheduleBuilder" /> that will be used to define the /// Trigger's schedule. /// </summary> /// <remarks> /// <para>The particular <see cref="IScheduleBuilder" /> used will dictate /// the concrete type of Trigger that is produced by the TriggerBuilder.</para> /// </remarks> /// <param name="scheduleBuilder">the SchedulerBuilder to use.</param> /// <returns>the updated TriggerBuilder</returns> /// <seealso cref="IScheduleBuilder" /> /// <seealso cref="SimpleScheduleBuilder" /> /// <seealso cref="CronScheduleBuilder" /> /// <seealso cref="CalendarIntervalScheduleBuilder" /> public TriggerBuilder WithSchedule(IScheduleBuilder scheduleBuilder) { this.scheduleBuilder = scheduleBuilder; return this; }
public IServiceCollectionTriggerConfigurator WithSchedule(IScheduleBuilder scheduleBuilder) { triggerBuilder.WithSchedule(scheduleBuilder); return(this); }