Пример #1
0
        public ActionResult Edit(int id)
        {
            var profile = _importProfileService.GetImportProfileById(id);

            if (profile == null)
            {
                return(RedirectToAction("List"));
            }

            var model = new ImportProfileModel();

            PrepareProfileModel(model, profile, _scheduleTaskService.GetLastHistoryEntryByTaskId(profile.SchedulingTaskId, true), true);

            return(View(model));
        }
Пример #2
0
        public ActionResult Edit(int id)
        {
            if (!Services.Permissions.Authorize(StandardPermissionProvider.ManageImports))
            {
                return(AccessDeniedView());
            }

            var profile = _importProfileService.GetImportProfileById(id);

            if (profile == null)
            {
                return(RedirectToAction("List"));
            }

            var model = new ImportProfileModel();

            PrepareProfileModel(model, profile, _scheduleTaskService.GetLastHistoryEntryByTaskId(profile.SchedulingTaskId, true), true);

            return(View(model));
        }
Пример #3
0
        public ActionResult RunJob(int id, string returnUrl = "")
        {
            if (!Services.Permissions.Authorize(StandardPermissionProvider.ManageScheduleTasks))
            {
                return(AccessDeniedView());
            }

            var taskParams = new Dictionary <string, string>
            {
                { TaskExecutor.CurrentCustomerIdParamName, Services.WorkContext.CurrentCustomer.Id.ToString() },
                { TaskExecutor.CurrentStoreIdParamName, Services.StoreContext.CurrentStore.Id.ToString() }
            };

            _taskScheduler.RunSingleTask(id, taskParams);

            // The most tasks are completed rather quickly. Wait a while...
            Thread.Sleep(200);

            // ...check and return suitable notifications
            var lastEntry = _scheduleTaskService.GetLastHistoryEntryByTaskId(id);

            if (lastEntry != null)
            {
                if (lastEntry.IsRunning)
                {
                    NotifyInfo(GetTaskMessage(lastEntry.ScheduleTask, "Admin.System.ScheduleTasks.RunNow.Progress"));
                }
                else
                {
                    if (lastEntry.Error.HasValue())
                    {
                        NotifyError(lastEntry.Error);
                    }
                    else
                    {
                        NotifySuccess(GetTaskMessage(lastEntry.ScheduleTask, "Admin.System.ScheduleTasks.RunNow.Success"));
                    }
                }
            }

            return(RedirectToReferrer(returnUrl));
        }
Пример #4
0
        public async Task <ActionResult> Sweep()
        {
            if (!_taskScheduler.VerifyAuthToken(Request.Headers["X-AUTH-TOKEN"]))
            {
                return(new HttpUnauthorizedResult());
            }

            var pendingTasks = await _scheduleTaskService.GetPendingTasksAsync();

            var count          = 0;
            var taskParameters = QueryString.Current.ToDictionary();

            if (pendingTasks.Count > 0)
            {
                Virtualize(taskParameters);
            }

            for (var i = 0; i < pendingTasks.Count; i++)
            {
                var task = pendingTasks[i];

                if (i > 0 /*&& (DateTime.UtcNow - _sweepStart).TotalMinutes > _taskScheduler.SweepIntervalMinutes*/)
                {
                    // Maybe a subsequent Sweep call or another machine in a webfarm executed
                    // successive tasks already.
                    // To be able to determine this, we need to reload the entity from the database.
                    // The TaskExecutor will exit when the task should be in running state then.
                    _services.DbContext.ReloadEntity(task);
                    task.LastHistoryEntry = _scheduleTaskService.GetLastHistoryEntryByTaskId(task.Id);
                }

                if (task.IsPending)
                {
                    await _taskExecutor.ExecuteAsync(task, taskParameters);

                    count++;
                }
            }

            return(Content("{0} of {1} pending tasks executed".FormatInvariant(count, pendingTasks.Count)));
        }
Пример #5
0
        public void Execute(
            ScheduleTask task,
            IDictionary <string, string> taskParameters = null,
            bool throwOnError = false)
        {
            if (AsyncRunner.AppShutdownCancellationToken.IsCancellationRequested)
            {
                return;
            }

            if (task.LastHistoryEntry == null)
            {
                // The task was started manually.
                task.LastHistoryEntry = _scheduledTaskService.GetLastHistoryEntryByTaskId(task.Id);
            }

            if (task?.LastHistoryEntry?.IsRunning == true)
            {
                return;
            }

            bool      faulted   = false;
            bool      canceled  = false;
            string    lastError = null;
            ITask     instance  = null;
            string    stateName = null;
            Type      taskType  = null;
            Exception exception = null;

            var historyEntry = new ScheduleTaskHistory
            {
                ScheduleTaskId = task.Id,
                IsRunning      = true,
                MachineName    = _env.MachineName,
                StartedOnUtc   = DateTime.UtcNow
            };

            try
            {
                taskType = Type.GetType(task.Type);
                if (taskType == null)
                {
                    Logger.DebugFormat("Invalid scheduled task type: {0}", task.Type.NaIfEmpty());
                }

                if (taskType == null)
                {
                    return;
                }

                if (!PluginManager.IsActivePluginAssembly(taskType.Assembly))
                {
                    return;
                }

                task.ScheduleTaskHistory.Add(historyEntry);
                _scheduledTaskService.UpdateTask(task);
            }
            catch
            {
                return;
            }

            try
            {
                // Task history entry has been successfully added, now we execute the task.
                // Create task instance.
                instance  = _taskResolver(taskType);
                stateName = task.Id.ToString();

                // Create & set a composite CancellationTokenSource which also contains the global app shoutdown token.
                var cts = CancellationTokenSource.CreateLinkedTokenSource(AsyncRunner.AppShutdownCancellationToken, new CancellationTokenSource().Token);
                _asyncState.SetCancelTokenSource <ScheduleTask>(cts, stateName);

                var ctx = new TaskExecutionContext(_componentContext, historyEntry)
                {
                    ScheduleTaskHistory = historyEntry.Clone(),
                    CancellationToken   = cts.Token,
                    Parameters          = taskParameters ?? new Dictionary <string, string>()
                };

                Logger.DebugFormat("Executing scheduled task: {0}", task.Type);
                instance.Execute(ctx);
            }
            catch (Exception ex)
            {
                exception = ex;
                faulted   = true;
                canceled  = ex is OperationCanceledException;
                lastError = ex.Message.Truncate(995, "...");

                if (canceled)
                {
                    Logger.Warn(ex, T("Admin.System.ScheduleTasks.Cancellation", task.Name));
                }
                else
                {
                    Logger.Error(ex, string.Concat(T("Admin.System.ScheduleTasks.RunningError", task.Name), ": ", ex.Message));
                }
            }
            finally
            {
                var now        = DateTime.UtcNow;
                var updateTask = false;

                historyEntry.IsRunning       = false;
                historyEntry.ProgressPercent = null;
                historyEntry.ProgressMessage = null;
                historyEntry.Error           = lastError;
                historyEntry.FinishedOnUtc   = now;

                if (faulted)
                {
                    if ((!canceled && task.StopOnError) || instance == null)
                    {
                        task.Enabled = false;
                        updateTask   = true;
                    }
                }
                else
                {
                    historyEntry.SucceededOnUtc = now;
                }

                try
                {
                    Logger.DebugFormat("Executed scheduled task: {0}. Elapsed: {1} ms.", task.Type, (now - historyEntry.StartedOnUtc).TotalMilliseconds);

                    // Remove from AsyncState.
                    if (stateName.HasValue())
                    {
                        _asyncState.Remove <ScheduleTask>(stateName);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex);
                }

                if (task.Enabled)
                {
                    task.NextRunUtc = _scheduledTaskService.GetNextSchedule(task);
                    updateTask      = true;
                }

                _scheduledTaskService.UpdateHistoryEntry(historyEntry);

                if (updateTask)
                {
                    _scheduledTaskService.UpdateTask(task);
                }

                Throttle.Check("Delete old schedule task history entries", TimeSpan.FromDays(1), () => _scheduledTaskService.DeleteHistoryEntries() > 0);
            }

            if (throwOnError && exception != null)
            {
                throw exception;
            }
        }