public void ValidateQueueName_DoesntThrowAnException_WhenValueHasOnlyDigits()
 {
     // Does not throw
     EnqueuedState.ValidateQueueName("queue", "363463");
 }
 public void ValidateQueueName_DoesntThrowAnException_WhenQueueNameHasOnlyLowerCaseLetters()
 {
     // Does not throw
     EnqueuedState.ValidateQueueName("queue", "valid");
 }
 public void ValidateQueueName_DoesntThrowAnException_WhenQueueNameHasUnderscores()
 {
     // Does not throw
     EnqueuedState.ValidateQueueName("queue", "a_b_c");
 }
 public void ValidateQueueName_ThrowsAnException_WhenQueueNameHasUpperCaseLetters()
 {
     Assert.Throws <ArgumentException>(() => EnqueuedState.ValidateQueueName("queue", "UppercaseLetters"));
 }
 public void ValidateQueueName_ThrowsAnException_WhenQueueNameHasWhitespaces()
 {
     Assert.Throws <ArgumentException>(() => EnqueuedState.ValidateQueueName("queue", "test test"));
 }
コード例 #6
0
        public void StateName_IsCorrect()
        {
            var state = new EnqueuedState();

            Assert.Equal(EnqueuedState.StateName, state.Name);
        }
コード例 #7
0
 public void ValidateQueueName_DoesntThrowAnException_WhenQueueNameHasOnlyLowerCaseLetters()
 {
     Assert.DoesNotThrow(() => EnqueuedState.ValidateQueueName("queue", "valid"));
 }
コード例 #8
0
        public void SetQueue_ThrowsAnException_WhenQueueValueIsEmpty()
        {
            var state = new EnqueuedState();

            Assert.Throws <ArgumentNullException>(() => state.Queue = String.Empty);
        }
コード例 #9
0
        public void IsFinal_ReturnsFalse()
        {
            var state = new EnqueuedState();

            Assert.False(state.IsFinal);
        }
コード例 #10
0
    static void Main(string[] args)
    {
        EnqueuedState queue = new EnqueuedState("myQueueName");

        new BackgroundJobClient().Create <Program>(c => c.DoWork(), queue);
    }
コード例 #11
0
        private void TryScheduleJob(
            JobStorage storage,
            IStorageConnection connection,
            string recurringJobId,
            IReadOnlyDictionary <string, string> recurringJob)
        {
            var serializedJob = JobHelper.FromJson <InvocationData>(recurringJob["Job"]);
            var job           = serializedJob.Deserialize();
            var cron          = recurringJob["Cron"];
            var cronSchedule  = CrontabSchedule.Parse(cron);

            try
            {
                var timeZone = recurringJob.ContainsKey("TimeZoneId")
                    ? TimeZoneInfo.FindSystemTimeZoneById(recurringJob["TimeZoneId"])
                    : TimeZoneInfo.Utc;

                var nowInstant    = _instantFactory(cronSchedule, timeZone);
                var changedFields = new Dictionary <string, string>();

                var lastInstant = GetLastInstant(recurringJob, nowInstant);

                if (nowInstant.GetNextInstants(lastInstant).Any())
                {
                    var state = new EnqueuedState {
                        Reason = "Triggered by recurring job scheduler"
                    };
                    if (recurringJob.ContainsKey("Queue") && !String.IsNullOrEmpty(recurringJob["Queue"]))
                    {
                        state.Queue = recurringJob["Queue"];
                    }

                    var backgroundJob = _factory.Create(new CreateContext(storage, connection, job, state));
                    var jobId         = backgroundJob != null ? backgroundJob.Id : null;

                    if (String.IsNullOrEmpty(jobId))
                    {
                        Logger.DebugFormat(
                            "Recurring job '{0}' execution at '{1}' has been canceled.",
                            recurringJobId,
                            nowInstant.NowInstant);
                    }

                    changedFields.Add("LastExecution", JobHelper.SerializeDateTime(nowInstant.NowInstant));
                    changedFields.Add("LastJobId", jobId ?? String.Empty);
                }

                // Fixing old recurring jobs that doesn't have the CreatedAt field
                if (!recurringJob.ContainsKey("CreatedAt"))
                {
                    changedFields.Add("CreatedAt", JobHelper.SerializeDateTime(nowInstant.NowInstant));
                }

                changedFields.Add("NextExecution", nowInstant.NextInstant.HasValue ? JobHelper.SerializeDateTime(nowInstant.NextInstant.Value) : null);

                connection.SetRangeInHash(
                    String.Format("recurring-job:{0}", recurringJobId),
                    changedFields);
            }
            catch (TimeZoneNotFoundException ex)
            {
                Logger.ErrorException(
                    String.Format("Recurring job '{0}' was not triggered: {1}.", recurringJobId, ex.Message),
                    ex);
            }
        }
コード例 #12
0
        public string Enqueue(Expression <Func <Task> > job, string queueName)
        {
            var state = new EnqueuedState(queueName);

            return(this.backgroundJobClient.Create(job, state));
        }
コード例 #13
0
 public void ValidateQueueName_DoesntThrowAnException_WhenValueHasOnlyDigits()
 {
     Assert.DoesNotThrow(() => EnqueuedState.ValidateQueueName("queue", "363463"));
 }
コード例 #14
0
 public void ValidateQueueName_DoesntThrowAnException_WhenQueueNameHasUnderscores()
 {
     Assert.DoesNotThrow(() => EnqueuedState.ValidateQueueName("queue", "a_b_c"));
 }
 public void ValidateQueueName_ThrowsAnException_WhenQueueNameIsEmpty()
 {
     Assert.Throws <ArgumentNullException>(() => EnqueuedState.ValidateQueueName("queue", string.Empty));
 }
コード例 #16
0
        public void IgnoreExceptions_ReturnsFalse()
        {
            var state = new EnqueuedState();

            Assert.False(state.IgnoreJobLoadException);
        }
コード例 #17
0
        private void TryScheduleJob(
            JobStorage storage,
            IStorageConnection connection,
            string recurringJobId,
            IReadOnlyDictionary <string, string> recurringJob)
        {
            var serializedJob = JobHelper.FromJson <InvocationData>(recurringJob["Job"]);
            var job           = serializedJob.Deserialize();
            var cron          = recurringJob["Cron"];
            var cronSchedule  = CrontabSchedule.Parse(cron);

            try
            {
                var timeZone = recurringJob.ContainsKey("TimeZoneId")
                    ? TimeZoneInfo.FindSystemTimeZoneById(recurringJob["TimeZoneId"])
                    : TimeZoneInfo.Utc;

                var nowInstant    = _instantFactory(cronSchedule, timeZone);
                var changedFields = new Dictionary <string, string>();

                var lastInstant = GetLastInstant(recurringJob, nowInstant);

                if (nowInstant.GetNextInstants(lastInstant).Any())
                {
                    var state = new EnqueuedState {
                        Reason = "Triggered by recurring job scheduler"
                    };
                    if (recurringJob.ContainsKey("Queue") && !String.IsNullOrEmpty(recurringJob["Queue"]))
                    {
                        state.Queue = recurringJob["Queue"];
                    }

                    var context = new CreateContext(storage, connection, job, state);
                    context.Parameters["RecurringJobId"] = recurringJobId;

                    var backgroundJob = _factory.Create(context);
                    var jobId         = backgroundJob?.Id;

                    if (String.IsNullOrEmpty(jobId))
                    {
                        _logger.Debug($"Recurring job '{recurringJobId}' execution at '{nowInstant.NowInstant}' has been canceled.");
                    }

                    changedFields.Add("LastExecution", JobHelper.SerializeDateTime(nowInstant.NowInstant));
                    changedFields.Add("LastJobId", jobId ?? String.Empty);
                }

                // Fixing old recurring jobs that doesn't have the CreatedAt field
                if (!recurringJob.ContainsKey("CreatedAt"))
                {
                    changedFields.Add("CreatedAt", JobHelper.SerializeDateTime(nowInstant.NowInstant));
                }

                changedFields.Add("NextExecution", nowInstant.NextInstant.HasValue ? JobHelper.SerializeDateTime(nowInstant.NextInstant.Value) : null);

                connection.SetRangeInHash(
                    $"recurring-job:{recurringJobId}",
                    changedFields);
            }
#if NETFULL
            catch (TimeZoneNotFoundException ex)
            {
#else
            catch (Exception ex)
            {
                // https://github.com/dotnet/corefx/issues/7552
                if (!ex.GetType().Name.Equals("TimeZoneNotFoundException"))
                {
                    throw;
                }
#endif

                _logger.ErrorException(
                    $"Recurring job '{recurringJobId}' was not triggered: {ex.Message}.",
                    ex);
            }
        }
 public void ValidateQueueName_ThrowsAnException_WhenQueueNameIsNull()
 {
     Assert.Throws <ArgumentNullException>(() => EnqueuedState.ValidateQueueName("queue", null));
 }
コード例 #19
0
        public void Ctor_ShouldSetQueue_WhenItWasGiven()
        {
            var state = new EnqueuedState("critical");

            Assert.Equal("critical", state.Queue);
        }
コード例 #20
0
        private void TryScheduleJob(
            JobStorage storage,
            IStorageConnection connection,
            string recurringJobId,
            IReadOnlyDictionary <string, string> recurringJob)
        {
            var serializedJob = JobHelper.FromJson <InvocationData>(recurringJob["Job"]);
            var job           = serializedJob.Deserialize();
            var cron          = recurringJob["Cron"];
            var cronSchedule  = CrontabSchedule.Parse(cron, _cronStringFormat);

            try
            {
                var startDate = JobHelper.DeserializeNullableDateTime(recurringJob["StartDate"]);
                if (startDate.HasValue)
                {
                    startDate = DateTime.SpecifyKind(startDate.Value, DateTimeKind.Utc);
                }

                var endDate = JobHelper.DeserializeNullableDateTime(recurringJob["EndDate"]);
                if (endDate.HasValue)
                {
                    endDate = DateTime.SpecifyKind(endDate.Value, DateTimeKind.Utc);
                }

                var ignoreEndDateTimeComponent = _ignoreTimeComponentInStartEndDates;
                if (recurringJob.ContainsKey(HashKeys.UseEndDateTimeComponent))
                {
                    bool.TryParse(recurringJob[HashKeys.UseEndDateTimeComponent] ?? bool.FalseString,
                                  out var useEndDateTimeComponent);
                    ignoreEndDateTimeComponent = !useEndDateTimeComponent;
                }

                var timeZone = recurringJob.ContainsKey("TimeZoneId")
                    ? TimeZoneInfo.FindSystemTimeZoneById(recurringJob["TimeZoneId"])
                    : TimeZoneInfo.Utc;

                var startDateForZone = startDate == null ? (DateTime?)null : TimeZoneInfo.ConvertTime(startDate.Value, TimeZoneInfo.Utc, timeZone);
                var endDateForZone   = endDate == null ? (DateTime?)null : TimeZoneInfo.ConvertTime(endDate.Value, TimeZoneInfo.Utc, timeZone);

                var nowInstant        = _instantFactory(cronSchedule, timeZone);
                var nowInstantForZone = TimeZoneInfo.ConvertTime(nowInstant.NowInstant, TimeZoneInfo.Utc, timeZone);

                // If the time component should be ignored, ignore it.
                if (_ignoreTimeComponentInStartEndDates && startDateForZone.HasValue)
                {
                    startDateForZone = startDateForZone.Value.Date;
                    // Now that we have the proper date, re-adjust the UTC versions so GetNextInstants works with the proper date range
                    startDate = TimeZoneInfo.ConvertTime(startDateForZone.Value, timeZone, TimeZoneInfo.Utc);
                }

                if (endDateForZone.HasValue && ignoreEndDateTimeComponent)
                {
                    endDateForZone = (endDateForZone.Value.Date == DateTime.MaxValue.Date)
                        ? DateTime.MaxValue
                        : endDateForZone.Value.Date.AddDays(1);
                    // Now that we have the proper date, re-adjust the UTC versions so GetNextInstants works with the proper date range
                    endDate = TimeZoneInfo.ConvertTime(endDateForZone.Value, timeZone, TimeZoneInfo.Utc);
                }

                var changedFields = new Dictionary <string, string>();

                var lastInstant = GetLastInstant(recurringJob, nowInstant, startDate, endDate);

                if (WithinDateRange(nowInstantForZone, startDateForZone, endDateForZone) && nowInstant.GetNextInstants(lastInstant, endDate).Any())
                {
                    var state = new EnqueuedState {
                        Reason = "Triggered by recurring job scheduler"
                    };
                    if (recurringJob.ContainsKey("Queue") && !String.IsNullOrEmpty(recurringJob["Queue"]))
                    {
                        state.Queue = recurringJob["Queue"];
                    }

                    var context = new CreateContext(storage, connection, job, state);
                    context.Parameters["RecurringJobId"] = recurringJobId;

                    var backgroundJob = _factory.Create(context);
                    var jobId         = backgroundJob?.Id;

                    if (String.IsNullOrEmpty(jobId))
                    {
                        Logger.Debug($"Recurring job '{recurringJobId}' execution at '{nowInstant.NowInstant}' has been canceled.");
                    }

                    changedFields.Add("LastExecution", JobHelper.SerializeDateTime(nowInstant.NowInstant));
                    changedFields.Add("LastJobId", jobId ?? String.Empty);
                }

                // Fixing old recurring jobs that doesn't have the CreatedAt field
                if (!recurringJob.ContainsKey("CreatedAt"))
                {
                    changedFields.Add("CreatedAt", JobHelper.SerializeDateTime(nowInstant.NowInstant));
                }

                changedFields.Add("NextExecution", nowInstant.NextInstant.HasValue ? JobHelper.SerializeDateTime(nowInstant.NextInstant.Value) : null);

                connection.SetRangeInHash(
                    $"{PluginConstants.JobType}:{recurringJobId}",
                    changedFields);
            }
#if NETFULL
            catch (TimeZoneNotFoundException ex)
            {
#else
            catch (Exception ex)
            {
                // https://github.com/dotnet/corefx/issues/7552
                if (!ex.GetType().Name.Equals("TimeZoneNotFoundException"))
                {
                    throw;
                }
#endif

                Logger.ErrorException(
                    $"Recurring job '{recurringJobId}' was not triggered: {ex.Message}.",
                    ex);
            }
        }