Beispiel #1
0
        public TaskExecutionContext(ITasklingConfiguration configuration,
                                    ITaskExecutionRepository taskExecutionRepository,
                                    ICriticalSectionRepository criticalSectionRepository,
                                    IBlockFactory blockFactory,
                                    IRangeBlockRepository rangeBlockRepository,
                                    IListBlockRepository listBlockRepository,
                                    IObjectBlockRepository objectBlockRepository,
                                    ICleanUpService cleanUpService,
                                    string applicationName,
                                    string taskName,
                                    TaskExecutionOptions taskExecutionOptions)
        {
            _configuration             = configuration;
            _taskExecutionRepository   = taskExecutionRepository;
            _criticalSectionRepository = criticalSectionRepository;
            _blockFactory          = blockFactory;
            _rangeBlockRepository  = rangeBlockRepository;
            _listBlockRepository   = listBlockRepository;
            _objectBlockRepository = objectBlockRepository;
            _cleanUpService        = cleanUpService;

            _taskExecutionInstance = new TaskExecutionInstance();
            _taskExecutionInstance.ApplicationName = applicationName;
            _taskExecutionInstance.TaskName        = taskName;

            _taskExecutionOptions = taskExecutionOptions;

            _executionHasFailed = false;

            _taskConfiguration = _configuration.GetTaskConfiguration(applicationName, taskName);
        }
Beispiel #2
0
        /// <summary>
        /// Queues the scheduled task.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="options">Task options</param>
        public void QueueScheduledTask <T>(TaskExecutionOptions options)
            where T : IScheduledTask
        {
            var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));

            QueueScheduledTask(scheduledTask, options);
        }
        private async Task ExecuteInternal(TaskExecutionOptions options)
        {
            // Cancel the current execution, if any
            if (CurrentCancellationTokenSource != null)
            {
                throw new InvalidOperationException("Cannot execute a Task that is already running");
            }

            var progress = new SimpleProgress <double>();

            CurrentCancellationTokenSource = new CancellationTokenSource();

            Logger.Info("Executing {0}", Name);

            ((TaskManager)TaskManager).OnTaskExecuting(this);

            progress.ProgressChanged += progress_ProgressChanged;

            TaskCompletionStatus status;

            CurrentExecutionStartTime = DateTime.UtcNow;

            Exception failureException = null;

            try
            {
                if (options != null && options.MaxRuntimeMs.HasValue)
                {
                    CurrentCancellationTokenSource.CancelAfter(options.MaxRuntimeMs.Value);
                }

                var localTask = ScheduledTask.Execute(CurrentCancellationTokenSource.Token, progress);

                await localTask.ConfigureAwait(false);

                status = TaskCompletionStatus.Completed;
            }
            catch (OperationCanceledException)
            {
                status = TaskCompletionStatus.Cancelled;
            }
            catch (Exception ex)
            {
                Logger.ErrorException("Error", ex);

                failureException = ex;

                status = TaskCompletionStatus.Failed;
            }

            var startTime = CurrentExecutionStartTime;
            var endTime   = DateTime.UtcNow;

            progress.ProgressChanged -= progress_ProgressChanged;
            CurrentCancellationTokenSource.Dispose();
            CurrentCancellationTokenSource = null;
            CurrentProgress = null;

            OnTaskCompleted(startTime, endTime, status, failureException);
        }
Beispiel #4
0
        /// <summary>
        /// Queues the scheduled task.
        /// </summary>
        /// <param name="task">The task.</param>
        /// <param name="options">The task options.</param>
        private void QueueScheduledTask(IScheduledTaskWorker task, TaskExecutionOptions options)
        {
            var type = task.ScheduledTask.GetType();

            lock (_taskQueue)
            {
                // If it's idle just execute immediately
                if (task.State == TaskState.Idle)
                {
                    Execute(task, options);
                    return;
                }

                if (!_taskQueue.ContainsKey(type))
                {
                    Logger.Info("Queueing task {0}", type.Name);
                    _taskQueue.Add(type, options);
                }
                else
                {
                    _taskQueue[type] = options;
                    Logger.Info("Task already queued: {0}", type.Name);
                }
            }
        }
Beispiel #5
0
        /// <summary>
        /// Cancels if running and queue.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="options">Task options.</param>
        public void CancelIfRunningAndQueue <T>(TaskExecutionOptions options)
            where T : IScheduledTask
        {
            var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));

            ((ScheduledTaskWorker)task).CancelIfRunning();

            QueueScheduledTask <T>(options);
        }
Beispiel #6
0
        public CriticalSectionContext(ICriticalSectionRepository criticalSectionRepository,
                                      TaskExecutionInstance taskExecutionInstance,
                                      TaskExecutionOptions taskExecutionOptions,
                                      CriticalSectionType criticalSectionType)
        {
            _criticalSectionRepository = criticalSectionRepository;
            _taskExecutionInstance     = taskExecutionInstance;
            _taskExecutionOptions      = taskExecutionOptions;
            _criticalSectionType       = criticalSectionType;

            ValidateOptions();
        }
Beispiel #7
0
        public override void SetupTest()
        {
            base.SetupTest();

            _fileSystemMock = AutoFixture.Freeze <Mock <IFileSystem> >();
            _processRunner  = AutoFixture.Freeze <Mock <IProcessRunner> >();
            _serverChannel  = AutoFixture.Freeze <Mock <IServerChannel> >();
            _options        = AutoFixture.Freeze <TaskExecutionOptions>();

            _serverChannel.Setup(s => s.WorkComplete(It.IsAny <TaskExecutionResult>())).Returns(new Response(false, ""));
            _taskExecutor = AutoFixture.Create <TaskExecutor>();
        }
Beispiel #8
0
        /// <summary>
        /// Queues the scheduled task.
        /// </summary>
        /// <param name="task">The task.</param>
        /// <param name="options">The task options.</param>
        public void QueueScheduledTask(IScheduledTask task, TaskExecutionOptions options)
        {
            var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == task.GetType());

            if (scheduledTask == null)
            {
                Logger.Error("Unable to find scheduled task of type {0} in QueueScheduledTask.", task.GetType().Name);
            }
            else
            {
                QueueScheduledTask(scheduledTask, options);
            }
        }
Beispiel #9
0
        /// <summary>
        /// Executes the task
        /// </summary>
        /// <param name="options">Task options.</param>
        /// <returns>Task.</returns>
        /// <exception cref="System.InvalidOperationException">Cannot execute a Task that is already running</exception>
        public async Task Execute(TaskExecutionOptions options)
        {
            var task = ExecuteInternal(options);

            _currentTask = task;

            try
            {
                await task.ConfigureAwait(false);
            }
            finally
            {
                _currentTask = null;
            }
        }
Beispiel #10
0
        private TaskExecutionOptions LoadTaskExecutionOptions(string applicationName, string taskName)
        {
            var taskConfiguration = _configuration.GetTaskConfiguration(applicationName, taskName);

            var executionOptions = new TaskExecutionOptions();

            executionOptions.TaskDeathMode           = taskConfiguration.UsesKeepAliveMode ? TaskDeathMode.KeepAlive : TaskDeathMode.Override;
            executionOptions.KeepAliveDeathThreshold = new TimeSpan((long)(taskConfiguration.KeepAliveDeathThresholdMinutes * TimeSpan.TicksPerMinute));
            executionOptions.KeepAliveInterval       = new TimeSpan((long)(taskConfiguration.KeepAliveIntervalMinutes * TimeSpan.TicksPerMinute));
            executionOptions.OverrideThreshold       = new TimeSpan((long)(taskConfiguration.TimePeriodDeathThresholdMinutes * TimeSpan.TicksPerMinute));
            executionOptions.ConcurrencyLimit        = taskConfiguration.ConcurrencyLimit;
            executionOptions.Enabled = taskConfiguration.Enabled;

            return(executionOptions);
        }
        /// <summary>
        /// Executes the task
        /// </summary>
        /// <param name="options">Task options.</param>
        /// <returns>Task.</returns>
        /// <exception cref="System.InvalidOperationException">Cannot execute a Task that is already running</exception>
        public async Task Execute(TaskExecutionOptions options)
        {
            var task = Task.Run(async() => await ExecuteInternal(options).ConfigureAwait(false));

            _currentTask = task;

            try
            {
                await task.ConfigureAwait(false);
            }
            finally
            {
                _currentTask = null;
                GC.Collect();
            }
        }
Beispiel #12
0
        /// <summary>
        /// Queues the scheduled task.
        /// </summary>
        /// <param name="task">The task.</param>
        /// <param name="options">The task options.</param>
        private void QueueScheduledTask(IScheduledTaskWorker task, TaskExecutionOptions options)
        {
            var type = task.ScheduledTask.GetType();

            Logger.Info("Queueing task {0}", type.Name);

            lock (_taskQueue)
            {
                if (task.State == TaskState.Idle && !SuspendTriggers)
                {
                    Execute(task, options);
                    return;
                }

                _taskQueue.Enqueue(new Tuple <Type, TaskExecutionOptions>(type, options));
            }
        }
Beispiel #13
0
 public Task Execute(IScheduledTaskWorker task, TaskExecutionOptions options)
 {
     return(((ScheduledTaskWorker)task).Execute(options));
 }
        /// <summary>
        /// Converts a TaskTriggerInfo into a concrete BaseTaskTrigger
        /// </summary>
        /// <param name="info">The info.</param>
        /// <returns>BaseTaskTrigger.</returns>
        /// <exception cref="System.ArgumentNullException"></exception>
        /// <exception cref="System.ArgumentException">Invalid trigger type:  + info.Type</exception>
        private ITaskTrigger GetTrigger(TaskTriggerInfo info)
        {
            var options = new TaskExecutionOptions
            {
                MaxRuntimeMs = info.MaxRuntimeMs
            };

            if (info.Type.Equals(typeof(DailyTrigger).Name, StringComparison.OrdinalIgnoreCase))
            {
                if (!info.TimeOfDayTicks.HasValue)
                {
                    throw new ArgumentNullException();
                }

                return(new DailyTrigger
                {
                    TimeOfDay = TimeSpan.FromTicks(info.TimeOfDayTicks.Value),
                    TaskOptions = options
                });
            }

            if (info.Type.Equals(typeof(WeeklyTrigger).Name, StringComparison.OrdinalIgnoreCase))
            {
                if (!info.TimeOfDayTicks.HasValue)
                {
                    throw new ArgumentNullException();
                }

                if (!info.DayOfWeek.HasValue)
                {
                    throw new ArgumentNullException();
                }

                return(new WeeklyTrigger
                {
                    TimeOfDay = TimeSpan.FromTicks(info.TimeOfDayTicks.Value),
                    DayOfWeek = info.DayOfWeek.Value,
                    TaskOptions = options
                });
            }

            if (info.Type.Equals(typeof(IntervalTrigger).Name, StringComparison.OrdinalIgnoreCase))
            {
                if (!info.IntervalTicks.HasValue)
                {
                    throw new ArgumentNullException();
                }

                return(new IntervalTrigger
                {
                    Interval = TimeSpan.FromTicks(info.IntervalTicks.Value),
                    TaskOptions = options
                });
            }

            if (info.Type.Equals(typeof(SystemEventTrigger).Name, StringComparison.OrdinalIgnoreCase))
            {
                if (!info.SystemEvent.HasValue)
                {
                    throw new ArgumentNullException();
                }

                return(new SystemEventTrigger(_systemEvents)
                {
                    SystemEvent = info.SystemEvent.Value,
                    TaskOptions = options
                });
            }

            if (info.Type.Equals(typeof(StartupTrigger).Name, StringComparison.OrdinalIgnoreCase))
            {
                return(new StartupTrigger());
            }

            throw new ArgumentException("Unrecognized trigger type: " + info.Type);
        }
Beispiel #15
0
        /// <summary>
        /// Queues the scheduled task.
        /// </summary>
        /// <param name="task">The task.</param>
        /// <param name="options">The task options.</param>
        public void QueueScheduledTask(IScheduledTask task, TaskExecutionOptions options)
        {
            var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == task.GetType());

            QueueScheduledTask(scheduledTask, options);
        }