コード例 #1
0
        public async Task Schedule_SetValidValue_SetsSchedule()
        {
            // Arrange
            using IJobManager jobManager = TestHelper.CreateJobManager(true);

            var start       = "2000-01-01Z".ToUtcDateOffset();
            var timeMachine = ShiftedTimeProvider.CreateTimeMachine(start);

            TimeProvider.Override(timeMachine);

            var name = "job1";
            var job  = jobManager.Create(name);

            job.IsEnabled = true;

            var writer = new StringWriterWithEncoding(Encoding.UTF8);

            job.Output = writer;

            // Act
            var newSchedule = new SimpleSchedule(SimpleScheduleKind.Second, 1, start.AddSeconds(2));

            job.Schedule = newSchedule;
            job.Routine  = (parameter, tracker, output, token) =>
            {
                output.Write("Hello!");
                return(Task.CompletedTask);
            };

            await timeMachine.WaitUntilSecondsElapse(start, 2.5);

            // Assert
            Assert.That(writer.ToString(), Is.EqualTo("Hello!"));
            Assert.That(job.Schedule, Is.SameAs(newSchedule));
        }
コード例 #2
0
        public void Schedule_SetValidValueForEnabledOrDisabledJob_SetsValue()
        {
            // Arrange
            using IJobManager jobManager = TestHelper.CreateJobManager(true);
            var job = jobManager.Create("my-job");

            var start       = "2000-01-01Z".ToUtcDateOffset();
            var timeMachine = ShiftedTimeProvider.CreateTimeMachine(start);

            TimeProvider.Override(timeMachine);

            ISchedule schedule1 = new SimpleSchedule(SimpleScheduleKind.Minute, 1, start);
            ISchedule schedule2 = new SimpleSchedule(SimpleScheduleKind.Day, 1, start);

            // Act
            job.Schedule = schedule1;
            var updatedSchedule1 = job.Schedule;
            var dueTime1         = job.GetInfo(null).NextDueTime;

            job.IsEnabled = true;

            job.Schedule = schedule2;
            var updatedSchedule2 = job.Schedule;
            var dueTime2         = job.GetInfo(null).NextDueTime;

            // Assert
            Assert.That(updatedSchedule1, Is.SameAs(schedule1));
            Assert.That(dueTime1, Is.EqualTo(start.AddMinutes(1)));

            Assert.That(updatedSchedule2, Is.SameAs(schedule2));
            Assert.That(dueTime2, Is.EqualTo(start.AddDays(1)));
        }
コード例 #3
0
        public async Task Schedule_DueTimeWasOverriddenThenScheduleIsSet_OverriddenDueTimeIsDiscardedAndScheduleIsSet()
        {
            // Arrange
            using IJobManager jobManager = TestHelper.CreateJobManager(true);
            var job = jobManager.Create("my-job");

            var start       = "2000-01-01Z".ToUtcDateOffset();
            var timeMachine = ShiftedTimeProvider.CreateTimeMachine(start);

            TimeProvider.Override(timeMachine);


            job.OverrideDueTime(start.AddSeconds(2.5));

            ISchedule schedule = new SimpleSchedule(SimpleScheduleKind.Second, 1, start);

            // Act
            await timeMachine.WaitUntilSecondsElapse(start, 1.8);

            job.Schedule = schedule;

            // Assert
            var info = job.GetInfo(null);

            Assert.That(info.NextDueTime, Is.EqualTo(start.AddSeconds(2)));
            Assert.That(info.NextDueTimeIsOverridden, Is.False);
        }
コード例 #4
0
        public void Schedule_SetThenDisposed_EqualsToLastOne()
        {
            // Arrange
            using IJobManager jobManager = TestHelper.CreateJobManager(true);
            var job = jobManager.Create("my-job");

            var start       = "2000-01-01Z".ToUtcDateOffset();
            var timeMachine = ShiftedTimeProvider.CreateTimeMachine(start);

            TimeProvider.Override(timeMachine);

            var schedule1 = new SimpleSchedule(SimpleScheduleKind.Second, 1, start);
            var schedule2 = new SimpleSchedule(SimpleScheduleKind.Minute, 1, start);
            var schedule3 = new SimpleSchedule(SimpleScheduleKind.Hour, 1, start);

            job.Schedule = schedule1;
            var readSchedule1 = job.Schedule;

            job.Schedule = schedule2;
            var readSchedule2 = job.Schedule;

            // Act
            job.Schedule = schedule3;
            job.Dispose();
            var readSchedule3 = job.Schedule;

            // Assert
            Assert.That(readSchedule1, Is.SameAs(schedule1));
            Assert.That(readSchedule2, Is.SameAs(schedule2));
            Assert.That(readSchedule3, Is.SameAs(schedule3));
        }
コード例 #5
0
        public async Task Schedule_SetAndStarted_ReflectedInCurrentRunAndUpdatesToNextDueTime()
        {
            // Arrange
            using IJobManager jobManager = TestHelper.CreateJobManager(true);

            var start       = "2000-01-01Z".ToUtcDateOffset();
            var timeMachine = ShiftedTimeProvider.CreateTimeMachine(start);

            TimeProvider.Override(timeMachine);

            var job = jobManager.Create("my-job");

            job.Routine = async(parameter, tracker, output, token) =>
            {
                await Task.Delay(10000, token); // long run
            };
            ISchedule schedule = new SimpleSchedule(SimpleScheduleKind.Second, 1, start);

            job.IsEnabled = true;

            // Act
            job.Schedule = schedule; // will fire at 00:01

            await timeMachine.WaitUntilSecondsElapse(start, 1.03);

            //await Task.Delay(1030); // let job start

            // Assert
            try
            {
                var info = job.GetInfo(null);
                var currentRunNullable = info.CurrentRun;

                Assert.That(currentRunNullable, Is.Not.Null); // todo: was null once :(
                var currentRun = currentRunNullable.Value;

                Assert.That(currentRun.StartReason, Is.EqualTo(JobStartReason.ScheduleDueTime));
                Assert.That(currentRun.DueTime, Is.EqualTo(start.AddSeconds(1)));
                Assert.That(currentRun.StartTime,
                            Is.EqualTo(start.AddSeconds(1)).Within(TimeSpan.FromMilliseconds(20)));

                // due time is 00:02 after start
                Assert.That(info.NextDueTime, Is.EqualTo(start.AddSeconds(2)));
            }
            catch (Exception ex)
            {
                var sb = new StringBuilder();
                sb.AppendLine("*** Test Failed ***");
                sb.AppendLine(ex.ToString());
                sb.AppendLine("*** Log: ***");

                var log = _logWriter.ToString();

                sb.AppendLine(log);

                Assert.Fail(sb.ToString());
            }
        }
コード例 #6
0
 public InitiateCalculateOfferCommand(ArrangementKind arrangementKind, string currency, decimal amount, decimal annuity,
                                      string term, decimal interestRate, decimal downpaymentAmount, decimal invoiceAmount, decimal minimalDownpaymentPercentage,
                                      string channel, decimal?riskScore, string creditRating, decimal?customerValue, decimal?debtToIncome, string customerSegment,
                                      string partOfBundle, string collateralModel, ProductConditions productConditions, Conditions conditions, LeadModel campaign,
                                      List <ProductOption> productOptions, Dictionary <string, JToken> bundledComponents, decimal downpaymentPercentage,
                                      List <ScheduledPeriod> scheduledPeriods, DateTime?calculationDate, DateTime?requestDate, DateTime?approvalDate,
                                      DateTime?signingDate, DateTime?disbursmentDate, DateTime?firstInstallmentDate, DateTime?maturityDate,
                                      string gracePeriod, DateTime?gracePeriodStartDate, string drawdownPeriod, DateTime?drawdownPeriodStartDate,
                                      RepaymentType?repaymentType, int numberOfInstallments, int minimumDaysForFirstInstallment, bool adjustFirstInstallment, bool payFeeFromDisbursement,
                                      SimpleSchedule installmentSchedule, IntercalarInterestRepaymentType intercalarInterestRepaymentType)
 {
     ArrangementKind                 = arrangementKind;
     Currency                        = currency;
     Amount                          = amount;
     Annuity                         = annuity;
     Term                            = term;
     InterestRate                    = interestRate;
     DownpaymentAmount               = downpaymentAmount;
     InvoiceAmount                   = invoiceAmount;
     MinimalDownpaymentPercentage    = minimalDownpaymentPercentage;
     Channel                         = channel;
     RiskScore                       = riskScore;
     CreditRating                    = creditRating;
     CustomerValue                   = customerValue;
     DebtToIncome                    = debtToIncome;
     CustomerSegment                 = customerSegment;
     PartOfBundle                    = partOfBundle;
     CollateralModel                 = collateralModel;
     ProductConditions               = productConditions;
     Conditions                      = conditions;
     Campaign                        = campaign;
     ProductOptions                  = productOptions;
     BundledComponents               = bundledComponents;
     DownpaymentPercentage           = downpaymentPercentage;
     ScheduledPeriods                = scheduledPeriods;
     CalculationDate                 = calculationDate ?? DateTime.Now;
     RequestDate                     = requestDate ?? DateTime.Now;
     ApprovalDate                    = approvalDate;
     SigningDate                     = signingDate;
     DisbursmentDate                 = disbursmentDate;
     FirstInstallmentDate            = firstInstallmentDate;
     MaturityDate                    = maturityDate;
     GracePeriod                     = gracePeriod;
     GracePeriodStartDate            = gracePeriodStartDate;
     DrawdownPeriod                  = drawdownPeriod;
     DrawdownPeriodStartDate         = drawdownPeriodStartDate;
     RepaymentType                   = repaymentType ?? Domain.Calculations.InstallmentPlanCalculation.RepaymentType.FixedAnnuity;
     NumberOfInstallments            = numberOfInstallments;
     MinimumDaysForFirstInstallment  = minimumDaysForFirstInstallment;
     AdjustFirstInstallment          = adjustFirstInstallment;
     PayFeeFromDisbursement          = payFeeFromDisbursement;
     InstallmentSchedule             = installmentSchedule;
     IntercalarInterestRepaymentType = intercalarInterestRepaymentType;
 }
コード例 #7
0
        public async Task Schedule_SetAndStartedAndCanceled_ReflectedInOldRuns()
        {
            // Arrange
            var DEFECT = TimeSpan.FromMilliseconds(30);

            using IJobManager jobManager = TestHelper.CreateJobManager(true);

            var start       = "2000-01-01Z".ToUtcDateOffset();
            var timeMachine = ShiftedTimeProvider.CreateTimeMachine(start);

            TimeProvider.Override(timeMachine);

            var job = jobManager.Create("my-job");

            job.Routine = async(parameter, tracker, output, token) =>
            {
                await Task.Delay(1500, token); // 1.5 second to complete
            };
            ISchedule schedule = new SimpleSchedule(SimpleScheduleKind.Second, 1, start);

            job.IsEnabled = true;

            // Act
            job.Schedule = schedule; // will fire at 00:01

            await timeMachine.WaitUntilSecondsElapse(start, 1.4 + DEFECT.TotalSeconds);

            var canceled = job.Cancel(); // will be canceled almost right after start

            Assert.That(canceled, Is.True);
            await Task.Delay(DEFECT); // let context finalize

            // Assert
            var info = job.GetInfo(null);

            Assert.That(info.CurrentRun, Is.Null);
            Assert.That(info.NextDueTime, Is.EqualTo(start.AddSeconds(2)));
            Assert.That(info.NextDueTimeIsOverridden, Is.False);

            var pastRun = info.Runs.Single();

            Assert.That(pastRun.RunIndex, Is.EqualTo(0));
            Assert.That(pastRun.StartReason, Is.EqualTo(JobStartReason.ScheduleDueTime));
            Assert.That(pastRun.DueTime, Is.EqualTo(start.AddSeconds(1)));
            Assert.That(pastRun.DueTimeWasOverridden, Is.False);

            Assert.That(pastRun.StartTime, Is.EqualTo(start.AddSeconds(1)).Within(DEFECT));
            Assert.That(
                pastRun.EndTime,
                Is.EqualTo(pastRun.StartTime.AddSeconds(0.4)).Within(DEFECT * 2));

            Assert.That(pastRun.Status, Is.EqualTo(JobRunStatus.Canceled));
        }
コード例 #8
0
        public async Task Dispose_JobsCreated_DisposesAndJobsAreCanceledAndDisposed()
        {
            // Arrange
            using IJobManager jobManager = TestHelper.CreateJobManager(true);

            var start = "2020-01-01Z".ToUtcDateOffset();

            TimeProvider.Override(ShiftedTimeProvider.CreateTimeMachine(start));


            var job1 = jobManager.Create("job1");

            job1.IsEnabled = true;

            var job2 = jobManager.Create("job2");

            job2.IsEnabled = true;

            job1.Output = new StringWriterWithEncoding(Encoding.UTF8);
            job2.Output = new StringWriterWithEncoding(Encoding.UTF8);

            async Task Routine(object parameter, IProgressTracker tracker, TextWriter output, CancellationToken token)
            {
                for (var i = 0; i < 100; i++)
                {
                    var time = TimeProvider.GetCurrentTime();
                    await output.WriteLineAsync($"Iteration {i}: {time.Second:D2}:{time.Millisecond:D3}");

                    try
                    {
                        await Task.Delay(1000, token);
                    }
                    catch (TaskCanceledException)
                    {
                        time = TimeProvider.GetCurrentTime();
                        await output.WriteLineAsync($"Canceled! {time.Second:D2}:{time.Millisecond:D3}");

                        throw;
                    }
                }
            }

            ISchedule schedule = new SimpleSchedule(
                SimpleScheduleKind.Second,
                1,
                start.AddMilliseconds(400));

            job1.Schedule = schedule;
            job2.Schedule = schedule;

            job1.Routine = Routine;
            job2.Routine = Routine;

            job1.IsEnabled = true;
            job2.IsEnabled = true;

            await Task.Delay(2500); // 3 iterations should be completed: ~400, ~1400, ~2400 todo: ut this

            // Act
            var jobInfoBeforeDispose1 = job1.GetInfo(null);
            var jobInfoBeforeDispose2 = job2.GetInfo(null);

            jobManager.Dispose();
            await Task.Delay(50); // let background TPL work get done.

            // Assert
            Assert.That(jobManager.IsDisposed, Is.True);

            foreach (var job in new[] { job1, job2 })
            {
                Assert.That(job.IsDisposed, Is.True);
                var info = job.GetInfo(null);
                var run  = info.Runs.Single();
                Assert.That(run.Status, Is.EqualTo(JobRunStatus.Canceled));
            }
        }
コード例 #9
0
        public static string Create(string name, string description, string data, string metaData, string jobType, string absoluteTimeout, string queueId, string application, string group, bool suppressHistory, bool deleteWhenDone, List <KeyValuePairStringString> additionalData, SimpleSchedule schedule)
        {
            try
            {
                TimeSpan?absoluteTimeoutValue = !string.IsNullOrEmpty(absoluteTimeout) ? (TimeSpan?)TimeSpan.Parse(absoluteTimeout) : null;
                byte     queueIdValue         = !string.IsNullOrEmpty(queueId) ? byte.Parse(queueId) : (byte)0;

                switch (jobType)
                {
                case "BackgroundWorkerService.Jobs.BasicHttpSoapCallbackJob, BackgroundWorkerService.Jobs":
                    string callbackUrl             = additionalData.First(d => d.Key == "callbackUrl").Value;
                    string contractType            = additionalData.First(d => d.Key == "contractType").Value;
                    string securityMode            = additionalData.First(d => d.Key == "securityMode").Value;
                    string credentialType          = additionalData.First(d => d.Key == "credentialType").Value;
                    string domain                  = additionalData.First(d => d.Key == "domain").Value;
                    string username                = additionalData.First(d => d.Key == "username").Value;
                    string password                = additionalData.First(d => d.Key == "password").Value;
                    string methodName              = additionalData.First(d => d.Key == "methodName").Value;
                    bool   ignoreCertificateErrors = bool.Parse(additionalData.First(d => d.Key == "ignoreCertificateErrors").Value);

                    try
                    {
                        Uri uri = new Uri(callbackUrl);
                    }
                    catch
                    {
                        throw new ArgumentException("Callback Url specified was not a valid Uri.");
                    }

                    if (contractType == "Basic")
                    {
                        metaData =
                            global::BackgroundWorkerService.Jobs.JobBuilder.CreateBasicHttpSoap_BasicCallbackJobMetaData(
                                metaData,
                                callbackUrl,
                                (System.ServiceModel.BasicHttpSecurityMode)Enum.Parse(typeof(System.ServiceModel.BasicHttpSecurityMode), securityMode),
                                (System.ServiceModel.HttpClientCredentialType)Enum.Parse(typeof(System.ServiceModel.HttpClientCredentialType), credentialType),
                                null,
                                domain,
                                username,
                                password,
                                ignoreCertificateErrors).Serialize();
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(methodName))
                        {
                            throw new ArgumentException("Method Name must be specified for Composite contracts.");
                        }
                        metaData =
                            global::BackgroundWorkerService.Jobs.JobBuilder.CreateBasicHttpSoap_CompositeBasicCallbackJobMetaData(
                                metaData,
                                methodName,
                                callbackUrl,
                                (System.ServiceModel.BasicHttpSecurityMode)Enum.Parse(typeof(System.ServiceModel.BasicHttpSecurityMode), securityMode),
                                (System.ServiceModel.HttpClientCredentialType)Enum.Parse(typeof(System.ServiceModel.HttpClientCredentialType), credentialType),
                                null,
                                domain,
                                username,
                                password,
                                ignoreCertificateErrors).Serialize();
                    }
                    break;

                case "BackgroundWorkerService.Jobs.SendMailJob, BackgroundWorkerService.Jobs":
                    string sendFrom    = additionalData.First(d => d.Key == "sendFrom").Value;
                    string sendTo      = additionalData.First(d => d.Key == "sendTo").Value;
                    string sendSubject = additionalData.First(d => d.Key == "sendSubject").Value;
                    string emailBody   = additionalData.First(d => d.Key == "emailBody").Value;

                    using (System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(sendFrom, sendTo, sendSubject, emailBody))
                    {
                        global::BackgroundWorkerService.Jobs.JobBuilder.GetSendMailJobDataAndMetaData(message, null, out data, out metaData);
                    }
                    break;
                }

                if (schedule == null)
                {
                    CreateNewJob(name, description, data, metaData, jobType, absoluteTimeoutValue, queueIdValue, application, group, suppressHistory, deleteWhenDone);
                }
                else
                {
                    ScheduleJob(name, description, data, metaData, jobType, absoluteTimeoutValue, queueIdValue, application, group, suppressHistory, deleteWhenDone, schedule);
                }
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
            return(string.Empty);
        }
コード例 #10
0
        private static void ScheduleJob(string name, string description, string data, string metaData, string jobType, TimeSpan?absoluteTimeout, byte queueId, string application, string group, bool suppressHistory, bool deleteWhenDone, SimpleSchedule schedule)
        {
            if (!schedule.StartDailyAt.HasValue)
            {
                schedule.StartDailyAt = new TimeSpan();
            }
            ScheduleJobRequest request = new ScheduleJobRequest
            {
                Application      = application,
                DeleteWhenDone   = deleteWhenDone,
                Description      = description,
                Name             = name,
                QueueId          = queueId,
                Type             = jobType,
                MetaData         = metaData,
                Data             = data,
                AbsoluteTimeout  = absoluteTimeout,
                Group            = group,
                CalendarSchedule = new CalendarSchedule
                {
                    ScheduleType = typeof(global::BackgroundWorkerService.Logic.DataModel.Scheduling.CalendarSchedule).AssemblyQualifiedName,
                    DaysOfWeek   = schedule.DaysOfWeek.ToArray(),
                    StartDailyAt = new TimeOfDay {
                        Hour = schedule.StartDailyAt.Value.Hours, Minute = schedule.StartDailyAt.Value.Minutes, Second = schedule.StartDailyAt.Value.Seconds
                    },
                    RepeatInterval = schedule.RepeatInterval,
                    EndDateTime    = null,
                    StartDateTime  = DateTime.Now,
                },
            };

            using (AccessPointClient client = new AccessPointClient())
            {
                client.ScheduleJob(request);
            }
        }
コード例 #11
0
        public async Task Schedule_SetDuringRun_DoesNotAffectRunButAppliesToDueTime()
        {
            // Arrange
            using IJobManager jobManager = TestHelper.CreateJobManager(true);

            var start       = "2000-01-01Z".ToUtcDateOffset();
            var timeMachine = ShiftedTimeProvider.CreateTimeMachine(start);

            TimeProvider.Override(timeMachine);

            var job       = jobManager.Create("my-job");
            var schedule1 = new SimpleSchedule(SimpleScheduleKind.Second, 1, start);

            job.Schedule = schedule1; // job will be started by due time of this schedule

            DateTimeOffset dueTime1 = default;
            DateTimeOffset dueTime2 = default;
            DateTimeOffset dueTime3 = default;
            DateTimeOffset dueTime4 = default;

            job.Routine = async(parameter, tracker, output, token) =>
            {
                Log.Debug("Entered routine.");

                // start + 1.2s: due time is (start + 2s), set by schedule1
                await timeMachine.WaitUntilSecondsElapse(start, 1.2, token);

                dueTime1 = job.GetInfo(0).NextDueTime; // should be 2s

                await timeMachine.WaitUntilSecondsElapse(start, 1.7, token);

                dueTime2 = job.GetInfo(0).NextDueTime;

                await timeMachine.WaitUntilSecondsElapse(start, 2.2, token);

                dueTime3 = job.GetInfo(0).NextDueTime;

                await timeMachine.WaitUntilSecondsElapse(start, 3.2, token);

                dueTime4 = job.GetInfo(0).NextDueTime;

                await Task.Delay(TimeSpan.FromHours(2), token);

                Log.Debug("Exited routine.");
            };

            job.IsEnabled = true;

            // Act
            var schedule2 = new SimpleSchedule(SimpleScheduleKind.Second, 1, start.AddSeconds(1.8));
            await timeMachine.WaitUntilSecondsElapse(start, 1.4);

            job.Schedule = schedule2;

            await timeMachine.WaitUntilSecondsElapse(start, 4);

            // Assert
            try
            {
                Assert.That(dueTime1, Is.EqualTo(start.AddSeconds(2)));
                Assert.That(dueTime2, Is.EqualTo(start.AddSeconds(1.8)));
                Assert.That(dueTime3, Is.EqualTo(start.AddSeconds(2.8)));
                Assert.That(dueTime4, Is.EqualTo(start.AddSeconds(3.8)));
            }
            catch (Exception ex)
            {
                var sb = new StringBuilder();
                sb.AppendLine("*** Test Failed ***");
                sb.AppendLine(ex.ToString());
                sb.AppendLine("*** Log: ***");

                var log = _logWriter.ToString();

                sb.AppendLine(log);

                Assert.Fail(sb.ToString());
            }
        }
コード例 #12
0
        public async Task Schedule_SetAndStartedAndFaulted_ReflectedInOldRuns()
        {
            // Arrange
            var DEFECT = TimeSpan.FromMilliseconds(30);

            using IJobManager jobManager = TestHelper.CreateJobManager(true);

            var start       = "2000-01-01Z".ToUtcDateOffset();
            var timeMachine = ShiftedTimeProvider.CreateTimeMachine(start);

            TimeProvider.Override(timeMachine);

            var job = jobManager.Create("my-job");

            job.Routine = async(parameter, tracker, output, token) =>
            {
                await Task.Delay(1500, token);              // 1.5 second runs with no problem...

                throw new ApplicationException("BAD_NEWS"); // ...and then throws!
            };
            ISchedule schedule = new SimpleSchedule(SimpleScheduleKind.Second, 1, start);

            job.IsEnabled = true;

            // Act
            job.Schedule = schedule; // will fire at 00:01

            await timeMachine.WaitUntilSecondsElapse(start,
                                                     2.8); // by this time, job will end due to the exception "BAD_NEWS" and finalize.

            // Assert
            var info = job.GetInfo(null);

            Assert.That(info.CurrentRun, Is.Null);



            Assert.That(info.NextDueTime, Is.EqualTo(start.AddSeconds(3)));
            // todo
            //Expected: 2000 - 01 - 01 00:00:03 + 00:00
            //But was:  2000 - 01 - 01 00:00:01 + 00:00



            Assert.That(info.NextDueTimeIsOverridden, Is.False);

            var pastRun = info.Runs.Single();

            Assert.That(pastRun.RunIndex, Is.EqualTo(0));
            Assert.That(pastRun.StartReason, Is.EqualTo(JobStartReason.ScheduleDueTime));
            Assert.That(pastRun.DueTime, Is.EqualTo(start.AddSeconds(1)));
            Assert.That(pastRun.DueTimeWasOverridden, Is.False);

            Assert.That(pastRun.StartTime, Is.EqualTo(start.AddSeconds(1)).Within(DEFECT));
            Assert.That(
                pastRun.EndTime,
                Is.EqualTo(pastRun.StartTime.AddSeconds(1.5)).Within(DEFECT * 2));

            Assert.That(pastRun.Status, Is.EqualTo(JobRunStatus.Faulted));
            Assert.That(pastRun.Exception, Is.TypeOf <ApplicationException>());
            Assert.That(pastRun.Exception, Has.Message.EqualTo("BAD_NEWS"));
        }
コード例 #13
0
        public async Task Schedule_SetAndStartedAndCompleted_ReflectedInOldRuns()
        {
            // Arrange
            var DEFECT = TimeSpan.FromMilliseconds(30);

            using IJobManager jobManager = TestHelper.CreateJobManager(true);

            var start       = "2000-01-01Z".ToUtcDateOffset();
            var timeMachine = ShiftedTimeProvider.CreateTimeMachine(start);

            TimeProvider.Override(timeMachine);

            var job = jobManager.Create("my-job");

            job.Routine = async(parameter, tracker, output, token) =>
            {
                await Task.Delay(1500, token); // 1.5 second to complete
            };
            ISchedule schedule = new SimpleSchedule(SimpleScheduleKind.Second, 1, start);

            job.IsEnabled = true;

            // Act
            job.Schedule = schedule; // will fire at 00:01

            await timeMachine.WaitUntilSecondsElapse(
                start,
                1.0 + DEFECT.TotalSeconds + 1.5 + DEFECT.TotalSeconds);

            // Assert
            try
            {
                var info = job.GetInfo(null);
                Assert.That(info.CurrentRun, Is.Null);

                Assert.That(info.NextDueTime, Is.EqualTo(start.AddSeconds(3)));

                var pastRun = info.Runs.Single();

                Assert.That(pastRun.RunIndex, Is.EqualTo(0));
                Assert.That(pastRun.StartReason, Is.EqualTo(JobStartReason.ScheduleDueTime));
                Assert.That(pastRun.DueTime, Is.EqualTo(start.AddSeconds(1)));
                Assert.That(pastRun.DueTimeWasOverridden, Is.False);

                Assert.That(pastRun.StartTime, Is.EqualTo(start.AddSeconds(1)).Within(DEFECT));
                Assert.That(
                    pastRun.EndTime,
                    Is.EqualTo(pastRun.StartTime.AddSeconds(1.5)).Within(DEFECT));

                Assert.That(pastRun.Status, Is.EqualTo(JobRunStatus.Completed));
            }
            catch (Exception ex)
            {
                // todo: need this block, here & in other places?
                // it is known now that the reason was slowpok TPL

                var sb = new StringBuilder();
                sb.AppendLine("*** Test Failed ***");
                sb.AppendLine(ex.ToString());
                sb.AppendLine("*** Log: ***");

                var log = _logWriter.ToString();

                sb.AppendLine(log);

                Assert.Fail(sb.ToString());
            }
        }
コード例 #14
0
        private static void CreateNewJob(Guid?uniqueId, string name, string description, string data, string metaData, string jobType, TimeSpan?absoluteTimeout, byte queueId, string application, string group, bool suppressHistory, bool deleteWhenDone, SimpleSchedule schedule)
        {
            CreateJobRequest request = new CreateJobRequest
            {
                UniqueId        = uniqueId,
                Application     = application,
                DeleteWhenDone  = deleteWhenDone,
                Description     = description,
                Name            = name,
                QueueId         = queueId,
                Type            = jobType,
                MetaData        = metaData,
                Data            = data,
                SuppressHistory = suppressHistory,
                AbsoluteTimeout = absoluteTimeout,
                Group           = group,
                Status          = JobStatus.Pending,
            };

            if (schedule != null)
            {
                if (!schedule.StartDailyAt.HasValue)
                {
                    schedule.StartDailyAt = new TimeSpan();
                }
                request.CalendarSchedule = new CalendarSchedule
                {
                    ScheduleType = typeof(global::BackgroundWorkerService.Logic.DataModel.Scheduling.CalendarSchedule).AssemblyQualifiedName,
                    DaysOfWeek   = schedule.DaysOfWeek.ToArray(),
                    StartDailyAt = new TimeOfDay {
                        Hour = schedule.StartDailyAt.Value.Hours, Minute = schedule.StartDailyAt.Value.Minutes, Second = schedule.StartDailyAt.Value.Seconds
                    },
                    RepeatInterval = schedule.RepeatInterval,
                    EndDateTime    = null,
                    StartDateTime  = !string.IsNullOrEmpty(schedule.StartDateTime) ? DateTime.ParseExact(schedule.StartDateTime, "dd-MM-yyyy HH:mm:ss", CultureInfo.CurrentCulture) : DateTime.Now,
                };
            }

            using (AccessPointClient client = new AccessPointClient())
            {
                client.CreateJob(request);
            }
        }
コード例 #15
0
        public static string UpdateJob(long jobId, string uniqueId, string name, string description, string data, string metaData, string statusId, string absoluteTimeout, string queueId, string application, string group, string suppressHistory, string deleteWhenDone, SimpleSchedule schedule)
        {
            try
            {
                JobData job = GetJob(jobId);
                if (job != null)
                {
                    if (!string.IsNullOrEmpty(statusId))
                    {
                        job.Status = (JobStatus)(int.Parse(statusId));
                    }

                    job.UniqueId    = Guid.Parse(uniqueId);
                    job.Name        = name;
                    job.Description = description;
                    job.Data        = data;
                    job.MetaData    = metaData;
                    if (!string.IsNullOrEmpty(absoluteTimeout))
                    {
                        job.AbsoluteTimeout = TimeSpan.Parse(absoluteTimeout);
                    }
                    if (!string.IsNullOrEmpty(queueId))
                    {
                        job.QueueId = byte.Parse(queueId);
                    }
                    job.Application     = application;
                    job.Group           = group;
                    job.SuppressHistory = bool.Parse(suppressHistory);
                    job.DeleteWhenDone  = bool.Parse(deleteWhenDone);

                    if (schedule != null)
                    {
                        if (!schedule.StartDailyAt.HasValue)
                        {
                            schedule.StartDailyAt = new TimeSpan();
                        }
                        job.CalendarSchedule = new CalendarSchedule
                        {
                            ScheduleType = typeof(global::BackgroundWorkerService.Logic.DataModel.Scheduling.CalendarSchedule).AssemblyQualifiedName,
                            DaysOfWeek   = schedule.DaysOfWeek.ToArray(),
                            StartDailyAt = new TimeOfDay {
                                Hour = schedule.StartDailyAt.Value.Hours, Minute = schedule.StartDailyAt.Value.Minutes, Second = schedule.StartDailyAt.Value.Seconds
                            },
                            RepeatInterval = schedule.RepeatInterval,
                            EndDateTime    = null,
                            StartDateTime  = !string.IsNullOrEmpty(schedule.StartDateTime) ? DateTime.ParseExact(schedule.StartDateTime, "dd-MM-yyyy HH:mm:ss", CultureInfo.CurrentCulture) : job.CalendarSchedule.StartDateTime,
                        };
                    }
                    else
                    {
                        job.CalendarSchedule = null;
                    }

                    using (AccessPointClient accessPoint = new AccessPointClient())
                    {
                        accessPoint.UpdateJob(new UpdateJobRequest {
                            JobData = job
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }
            return(string.Empty);
        }