Beispiel #1
0
        /// <summary>
        /// Позволяет зарегистрировать задачу. Если задача ранее была зарегистрирована, то обновляет параметры ранее зарегистрированной задачи.
        /// </summary>
        /// <returns>Возвращает зарегистрированную задачу.</returns>
        /// <exception cref="ArgumentNullException">Возникает, если <paramref name="taskRequest"/> равен null.</exception>
        /// <exception cref="ArgumentException">Возникает, если не указано имя задачи.</exception>
        /// <exception cref="ArgumentException">Возникает, если не указан уникальный ключ задачи.</exception>
        public TaskDescription RegisterTask(TaskRequest taskRequest)
        {
            if (taskRequest == null)
            {
                throw new ArgumentNullException(nameof(taskRequest));
            }
            if (string.IsNullOrEmpty(taskRequest.Name))
            {
                throw new ArgumentException("Имя задачи не может быть пустым.", nameof(taskRequest.Name));
            }
            if (string.IsNullOrEmpty(taskRequest.UniqueKey))
            {
                throw new ArgumentException("Уникальный ключ задачи не может быть пустым.", nameof(taskRequest.UniqueKey));
            }
            if (taskRequest.Schedules?.GroupBy(x => x.GetUniqueKey()).Any(x => x.Count() > 1) ?? false)
            {
                throw new ArgumentException("В задаче есть повторяющиеся правила запуска.", nameof(taskRequest.Schedules));
            }

            try
            {
                var taskDescription = _taskList.AddOrUpdate(taskRequest.UniqueKey,
                                                            key => UpdateTask(new TaskDescription(), taskRequest),
                                                            (key, old) => UpdateTask(old, taskRequest)
                                                            );
                PrepareTaskSchedules(taskDescription);
                return(taskDescription);
            }
            catch (Exception ex)
            {
                this.RegisterEvent(Journaling.EventType.CriticalError, "Ошибка во время регистрации задачи", null, ex);
                throw new Exception("Неожиданная ошибка во время регистрации задачи.");
            }
        }
Beispiel #2
0
        private TaskDescription UpdateTask(TaskDescription taskDescription, TaskRequest taskRequest)
        {
            using (var db = new Db.DataContext())
            {
                var taskDb = db.Task.Where(x => x.UniqueKey == taskRequest.UniqueKey).Include(x => x.TaskSchedules).FirstOrDefault();
                if (taskDb == null)
                {
                    taskDb = new Db.Task()
                    {
                        Name          = taskRequest.Name,
                        Description   = taskRequest.Description,
                        IsEnabled     = null,
                        TaskSchedules = new List <Db.TaskSchedule>(),
                        UniqueKey     = taskRequest.UniqueKey
                    };
                    db.Task.Add(taskDb);
                    db.SaveChanges();
                }

                taskDb.Name        = taskRequest.Name;
                taskDb.Description = taskRequest.Description;

                if (!taskRequest.TaskOptions.HasFlag(TaskOptions.AllowDisabling))
                {
                    taskDb.IsEnabled = null;
                }

                if (!taskRequest.TaskOptions.HasFlag(TaskOptions.AllowManualSchedule) && taskDb.TaskSchedules.Count > 0)
                {
                    db.TaskSchedule.RemoveRange(taskDb.TaskSchedules);
                    taskDb.TaskSchedules.Clear();
                }
                db.SaveChanges();

                var schedules = new List <TaskSchedule>();
                foreach (var scheduleDb in taskDb.TaskSchedules)
                {
                    TaskSchedule taskSchedule = null;
                    if (scheduleDb.DateTimeFixed.HasValue)
                    {
                        taskSchedule = new TaskFixedTimeSchedule(new DateTimeOffset(scheduleDb.DateTimeFixed.Value.Ticks, TimeSpan.Zero));
                    }
                    else if (!string.IsNullOrEmpty(scheduleDb.Cron))
                    {
                        taskSchedule = new TaskCronSchedule(scheduleDb.Cron);
                    }

                    if (taskSchedule == null)
                    {
                        continue;
                    }
                    taskSchedule.IsEnabled = scheduleDb.IsEnabled;
                    schedules.Add(taskSchedule);
                }

                taskDescription.Id              = taskDb.Id;
                taskDescription.Name            = taskRequest.Name;
                taskDescription.Description     = taskRequest.Description;
                taskDescription.ExecutionLambda = taskRequest.ExecutionLambda;
                taskDescription.IsConfirmed     = true;
                taskDescription.UniqueKey       = taskRequest.UniqueKey;
                taskDescription.IsEnabled       = taskDb.IsEnabled ?? taskRequest.IsEnabled;
                taskDescription.TaskOptions     = taskRequest.TaskOptions;
                taskDescription.Schedules       = new ReadOnlyCollection <TaskSchedule>(taskRequest.Schedules ?? new List <TaskSchedule>());
                taskDescription.ManualSchedules = new ReadOnlyCollection <TaskSchedule>(schedules.GroupBy(x => x.GetUniqueKey()).Select(x => x.First()).ToList());
                taskDescription.JournalOptions  = taskRequest.JournalOptions;
            }
            return(taskDescription);
        }