// This event was created to replace the event raised by CodeArmor which signifies product usage. // The event is created and scheduled to execute 1 hour later, similar to the CodeArmor event. public bool SendProductWorksStatistic() { try { if (!Tracker.IsReportingEnabled()) { return true; } const uint initialDelay = 3600000; const uint retryDelay = 300000; const uint retry = 5; var task = new TaskBase() { EventName = "After working time", Parameters = DefaultEventProperties.Instance.ExtendedProperties }; DelayedTask.Schedule(task, initialDelay, retryDelay, retry); return true; } catch (Exception ex) { Logger.LogError(ex); return false; } }
private async Task<WebTaskResult> Start(TaskBase task, Action<WebTaskResult> onComplete = null) { WebTaskResult r = new WebTaskResult { Success = false }; bool canExecute = task.Status != WebTaskStatus.Running; if (canExecute) { try { MusicRepository.SetRunning(task); SendMessage(new TaskStarted(task.TaskId, task.Name, task.StartedAt)); r = await task.Execute(); return r; } catch (Exception xe) { task.CompletionRemark = $"failed: {xe.Message}"; r.Exception = xe; this.Logger.LogError($"Task {task.Name} failed: {xe.Message}"); } finally { MusicRepository.SetFinished(task); if (onComplete != null) { onComplete(r); } SendMessage(new TaskFinished(task.TaskId, task.Name, task.FinishedAt, task.CompletionRemark)); } } else { r.IsRunning = true; } return r; }
public static void AddTask(TaskBase task, TaskScheduler scheduler) { if (_mainUiScheduler == null) _mainUiScheduler = scheduler; TaskFactory taskFactory = new TaskFactory(_mainUiScheduler); Task A = taskFactory.StartNew(task.Run); Task B = A.ContinueWith(t => { }, _mainUiScheduler); }
/// <summary> /// 把task封装给协程用,monoBeheivor 的yield return /// </summary> public static TaskYieldInstruction AsCoroutine(this TaskBase task) { if (task == null) { throw new NullReferenceException(); } return(new TaskYieldInstruction(task)); }
public void Reset() { var list = TaskBase.GetJobList(); foreach (var item in list) { BackgroundJob.Delete(item.Id.ToString()); } }
public void RemoveTask(TaskBase _task) { _tasks.Remove(_task); _charWindow.flowLayoutPanel1.Controls.Remove(_task.TaskWindow); _availableDBTasks.Add(_task.TaskDBEntry); _charWindow.comboBoxTasks.DataSource = null; _charWindow.comboBoxTasks.DataSource = _availableDBTasks; _charWindow.comboBoxTasks.DisplayMember = "TaskName"; }
public override void Update(float deltaTime) { if (IsPaused || IsFinished) { return; } if (isUpdateing) { //Debug.LogError("不能更新TaskList,当它正在更新的时候"); return; } base.Update(deltaTime); isUpdateing = true; for (int i = 0; i < tasks.Count; i++) { TaskBase task = tasks[i]; if (!task.IsFinished && !task.IsPaused) { task.Update(deltaTime); } //防止TaskList已经被Cancel if (this.IsFinished) { break; } if (task.IsFinished) { tasks.RemoveAt(i); if (task.HasLateUpate) { tasksLateUpate.Remove(task); } --i; continue; } index = i; if (isSerial) { break; } } if (tasks.Count == 0 && autoComplete) { Complete(); } isUpdateing = false; }
protected int _size; // size of tree, also used for new node id creation /// <summary> /// tree constructor /// </summary> public MgTreeBase(TaskBase task) { Task = task; if (Task.getForm() != null) { Task.getForm().setMgTree(this); } _allNodes = new Dictionary <int, NodeBase>(); }
public void LoadFinishedCallback(bool manual, TaskBase currentTask) { Object taizi = (Object)((AssetBundleLoadTask)currentTask).getTargetAsset(); GameObject new_taizi = (GameObject)Instantiate(taizi); new_taizi.layer = LayerMask.NameToLayer("UI"); new_taizi.transform.parent = TaiZi.transform; InitTaiZi(new_taizi.transform); UtilTools.UpdateShaders(new_taizi); }
private void UpdateTask(TaskBase task) { using (var database = new LiteDatabase(DataBasePath)) { var dataBaseTaskCollection = database.GetCollection <TaskDataBaseItem>(TaskCollectionName); TaskDataBaseItem dataBaseItem = taskToDataBaseMapper.GetDataBaseItemFromTask(task); taskToDataBaseMapper.UpdateItemInformation(dataBaseItem); dataBaseTaskCollection.Update(dataBaseItem); } }
/// <summary> /// </summary> /// <param name = "currTask"> </param> /// <returns> </returns> public static bool ClipboardWrite(TaskBase currTask) { // set a String to the clip. ClipboardWrite(null, _clipboardData); if (currTask.getLastParkedCtrl() != null) { currTask.ActionManager.checkPasteEnable(currTask.getLastParkedCtrl()); } return(true); }
/// <summary> /// Contructor /// </summary> /// <param name="updateDataViewToDataSourceCommand"></param> public LocalUpdateRemoteDataViewToDataSourceCommand(UpdateDataViewToDataSourceEventCommand updateDataViewToDataSourceCommand) : base(updateDataViewToDataSourceCommand) { this.updateDataViewToDataSourceCommand = updateDataViewToDataSourceCommand; this.destinationColumnList = updateDataViewToDataSourceCommand.DestinationDataSourceFieldsList; this.sourceVarList = updateDataViewToDataSourceCommand.SourceVarList; destinationToSourceFieldIndexMapping = new Dictionary <string, int>(); task = (TaskBase)MGDataCollection.Instance.GetTaskByID(updateDataViewToDataSourceCommand.TaskTag); destinationDataSourceDefinition = ClientManager.Instance.LocalManager.ApplicationDefinitions.DataSourceDefinitionManager.GetDataSourceDefinition(task.getCtlIdx(), updateDataViewToDataSourceCommand.DestDataSource); }
private void AddTask(TaskBase task) { using (var database = new LiteDatabase(DataBasePath)) { var dataBaseTaskCollection = database.GetCollection <TaskDataBaseItem>(TaskCollectionName); TaskDataBaseItem dataBaseItem = taskToDataBaseMapper.GetDataBaseItemFromTask(task); dataBaseTaskCollection.Insert(dataBaseItem); } }
//----------------------------------------------------------------// public async Task RunTask(TaskBase taskBase, IDbConnection connection) { bool isSuccess = await Task.Run(() => taskBase.SafeExecute(connection)); if (isSuccess) { _commandFactory.CreateCommand <ITaskInfoCommand>(connection) .Update(taskBase.taskInfo); } }
public void RemoveTask(long taskId) { int index; TaskBase task = _tasks.Tasks.TaskById(taskId, out index); if (task != null) { _tasks.Tasks.RemoveAt(index); } }
public void SetScheduleProperty(long taskId, string propertyName, string propertyValue) { if (Paused && propertyName == "Paused") { return; // ignore attempts to pause/resume schedules when service is paused. } TaskBase task = _tasks.Tasks.TaskById(taskId); Util.SetProperty(task.Schedule, propertyName, propertyValue); }
public bool CheckTask(long taskId, bool checkActions) { TaskBase task = _tasks.Tasks.TaskById(taskId); if (task != null) { return(task.Check(checkActions)); } return(false); }
// Start is called before the first frame update void Start() { _player = FindObjectOfType <PlayerController>(); // Fetch the task task = GetComponent <TaskBase>(); // Fetch the task manager _taskManager = FindObjectOfType <TaskManager>(); }
public TaskDefinitionId TaskCalledByMenu(int menuId, TaskBase mainProg) { //fixed bug#:431559, the menu need to be take from menuCtlIndex main program. ApplicationMenus applicationMenus = getApplicationMenus(mainProg); MenuEntryProgram menuEntry = applicationMenus.menuByUid(menuId) as MenuEntryProgram; TaskDefinitionId taskDefinitionId = new TaskDefinitionId(menuEntry.CtlIndex, menuEntry.ProgramIsn, 0, true); return(taskDefinitionId); }
/// <summary> /// Create MenuEntries for WindowList Items. /// </summary> /// <param name="guiMgForm"></param> /// <param name="guiMenuEntry"></param> /// <param name="menuStyle"></param> public void CreateWindowMenuEntries(GuiMgForm guiMgForm, Object guiMenuEntry, MenuStyle menuStyle) { Debug.Assert(Misc.IsGuiThread()); bool IsMenuEntryWindowMenu = guiMenuEntry is MenuEntryWindowMenu; MenuEntry menuEntry; int windowMenuIdx = 0; //We get this flag as true only when the menu contains WindowList at first level and it is being used as context menu if (IsMenuEntryWindowMenu) { //Here we add the new WindowMenu in the parent MgMenu menuEntry = (MenuEntryWindowMenu)guiMenuEntry; windowMenuIdx = menuEntry.getParentMgMenu().GetWindowMenuEntryIndex(); } else { //We add the WindowMenu in the MenuEntryMenu menuEntry = (MenuEntryMenu)guiMenuEntry; windowMenuIdx = ((MenuEntryMenu)menuEntry).GetWindowMenuEntryIndex(); } // Enable/Disable MenuEntries for CloseAll, NextWindow & PreviousWindow. TaskBase task = ((MgFormBase)guiMgForm).getTask(); MgMenu mgMenu = menuEntry.getParentMgMenu(); mgMenu.enableInternalEvent((MgFormBase)guiMgForm, InternalInterface.MG_ACT_CLOSE_ALL_WIN, task.ActionManager.isEnabled(InternalInterface.MG_ACT_CLOSE_ALL_WIN), null); mgMenu.enableInternalEvent((MgFormBase)guiMgForm, InternalInterface.MG_ACT_NEXT_RT_WINDOW, task.ActionManager.isEnabled(InternalInterface.MG_ACT_NEXT_RT_WINDOW), null); mgMenu.enableInternalEvent((MgFormBase)guiMgForm, InternalInterface.MG_ACT_PREV_RT_WINDOW, task.ActionManager.isEnabled(InternalInterface.MG_ACT_PREV_RT_WINDOW), null); lock (_windowListLock) { if (IsValidIndex(windowMenuIdx)) { // Delete the existing MenuEntries. DeleteWindowMenuEntries(menuEntry, windowMenuIdx + 1, IsMenuEntryWindowMenu); // Create new MenuEntries for WindowList Items. if (_windowList.Count > 0) { // Create menu item for a form in window list. for (int i = 0; i < _windowList.Count; i++) { MgFormBase mgForm = _windowList[i]; menuEntry.CreateMenuEntry(mgForm, GuiMenuEntry.MenuType.WINDOW_MENU_ENTRY, windowMenuIdx++, guiMgForm, menuStyle, _sortByRecentlyUsed ? i == 0 : i == _currWinIdx); } // Create a separator to distinguish the window menu items only for PullDown menu if (menuStyle != MenuStyle.MENU_STYLE_CONTEXT) { menuEntry.CreateMenuEntry(null, GuiMenuEntry.MenuType.SEPARATOR, windowMenuIdx++, guiMgForm, menuStyle, false); } } } } }
/// <summary> /// Builds the time windows for flight group. /// </summary> /// <param name="task">The task.</param> /// <returns></returns> private Queue <TimeWindow> InitializeTimeWindowsQueue(TaskBase task) { var returnVal = new Queue <TimeWindow>(); //Practice Window (3 minutes) returnVal.Enqueue(new TimeWindow { Name = "Flight Test Window", GateType = TimeGateType.Practice, DirectionOfCount = TimerDirection.CountDown, CountDownLast10Seconds = true, Time = new TimeSpan(0, 3, 0) }); //Task Window (build from the task object) foreach (var timeWindow in task.TaskFlightWindows) { var name = string.Empty; switch (timeWindow.GateType) { case TimeGateType.Break: name = $"{timeWindow.Time.TotalMinutes} before a 3 minute task."; break; case TimeGateType.Landing: name = $"{timeWindow.Time.TotalMinutes} minute landing Window. All aircraft must be on the ground in {timeWindow.Time.TotalMinutes} minute"; break; case TimeGateType.Task: name = $"Task Window"; break; } returnVal.Enqueue(new TimeWindow { Name = name, GateType = timeWindow.GateType, DirectionOfCount = timeWindow.DirectionOfCount, CountDownLast10Seconds = true, Time = timeWindow.Time }); } //Landing Window (30 seconds) returnVal.Enqueue(new TimeWindow { Name = "Landing Window", GateType = TimeGateType.Landing, DirectionOfCount = TimerDirection.CountDown, CountDownLast10Seconds = true, Time = new TimeSpan(0, 0, 30) }); return(returnVal); }
private async Task Start(JobTaskView view, TaskLoadContext lc) { //throw //在应用程序域中创建实例返回并保存在job中,这是最终调用任务执行的实例 TaskBase instance = AssemblyHelper.CreateTaskInstance(lc, view.JobTask.Id, view.JobTask.AssemblyName, view.JobTask.ClassName); if (instance == null) { throw new InvalidCastException($"任务实例创建失败,请确认目标任务是否派生自TaskBase类型。程序集:{view.JobTask.AssemblyName},类型:{view.JobTask.ClassName}"); } // instance.logger = new LogWriter(); ; JobDataMap map = new JobDataMap { new KeyValuePair <string, object> ("domain", lc), new KeyValuePair <string, object> ("instance", instance), new KeyValuePair <string, object> ("name", view.JobTask.Title), new KeyValuePair <string, object> ("params", ConvertParamsJson(view.JobTask.CustomParamsJson)), new KeyValuePair <string, object> ("keepers", view.Keepers), new KeyValuePair <string, object> ("children", view.Children) }; try { IJobDetail job = JobBuilder.Create <RootJob>() .WithIdentity(view.JobTask.Id.ToString()) .UsingJobData(map) .Build(); //添加触发器 var listener = new JobRunListener(view.JobTask.Id.ToString()); listener.OnSuccess += StartedEventAsync; _scheduler.ListenerManager.AddJobListener(listener, KeyMatcher <JobKey> .KeyEquals(new JobKey(view.JobTask.Id.ToString()))); if (!CronExpression.IsValidExpression(view.JobTask.CronExpression)) { throw new Exception("cron表达式验证失败"); } CronTriggerImpl trigger = new CronTriggerImpl { CronExpressionString = view.JobTask.CronExpression, Name = view.JobTask.Title, Key = new TriggerKey(view.JobTask.Id.ToString()), Description = view.JobTask.Remark }; await _scheduler.ScheduleJob(job, trigger); } catch (Exception ex) { throw new SchedulerException(ex); } _logger.LogInformation($"任务[{view.JobTask.Title}]启动成功!", view.JobTask.Id); }
private void RemoveTask(TaskBase task) { using (var database = new LiteDatabase(DataBasePath)) { var dataBaseTaskCollection = database.GetCollection <TaskDataBaseItem>(TaskCollectionName); TaskDataBaseItem dataBaseItem = taskToDataBaseMapper.GetDataBaseItemFromTask(task); taskToDataBaseMapper.DeleteItem(dataBaseItem); dataBaseTaskCollection.Delete(t => t == dataBaseItem); } }
public static TaskBase Copy(this TaskBase task) { return(new TaskBase() { Id = task.Id, Subject = task.Subject, Description = task.Description, CreationDate = task.CreationDate, Status = task.Status }); }
public string GetScheduleXml(long taskId) { Debug.Assert(_callback != null); TaskBase task = _tasks.Tasks.TaskById(taskId); if (task != null) { return(((ScheduleServer)task.Schedule).ToProxyXml()); } return(null); }
public SettingsGroupViewModel(Type componentType, IEnumerable <Type> taskSettings, string groupName) { Misc.FPReset(); _groupName = groupName; _settingsTypes = taskSettings; _taskInstance = Activator.CreateInstance(componentType) as TaskBase; _serviceSettings = GroupSettings.GetGroupSettings(_taskInstance, GroupName); RunTaskCommand = new RelayCommand(arg => RunTask()); RunTaskCurrentThreadCommand = new RelayCommand(arg => RunTaskCurrentThread()); SaveCommand = new RelayCommand(arg => _serviceSettings.SaveSettings()); }
public int GetActionCount(long taskId) { Debug.Assert(_callback != null); TaskBase task = _tasks.Tasks.TaskById(taskId); if (task != null) { return(task.Actions.Count); } return(0); }
/// <summary> /// Checks whether a task is available to do /// </summary> /// <param name="task">The task to check</param> /// <returns>Whether it has been completed</returns> public bool IsTaskAvailable(TaskBase task) { if (currentTask != null) { return(currentTask.GetType() == task.GetType()); } else { return(false); } }
/// <summary> /// Get pulldown Menu. /// </summary> /// <param name = "task"></param> private MgMenu GetPulldownMenu(TaskBase task) { MgFormBase formOrg = (MgFormBase)task.getTopMostForm(); MgFormBase form = (formOrg != null) ? (MgFormBase)formOrg.getTopMostFrameForm() : null; form = (form ?? formOrg); MgMenu pulldownMenu = (form != null) ? form.getPulldownMenu() : null; return(pulldownMenu); }
/// <summary> /// enable/disable menu entry identified by entryName. /// </summary> /// <param name = "task"></param> /// <param name = "entryName">menuentry name</param> /// <param name = "enable">enable/disable value</param> public bool MenuEnableByName(TaskBase task, String entryName, bool enable) { bool internalEventMenuEnabled = false; MgMenu pulldownMenu = GetPulldownMenu(task); // Get matching menus from all ctls ArrayList menuEntryList = GetMatchingMenuValues(task.ContextID, entryName, pulldownMenu); if (menuEntryList != null) { IEnumerator iMatchingEnt = menuEntryList.GetEnumerator(); while (iMatchingEnt.MoveNext()) { var menuValue = (MenuValue)iMatchingEnt.Current; var mnuEnt = menuValue.InnerMenuEntry; if (mnuEnt.menuType() == GuiMenuEntry.MenuType.INTERNAL_EVENT) { MenuEntryEvent menuEntryEvent = (MenuEntryEvent)mnuEnt; if ((menuEntryEvent.InternalEvent < InternalInterface.MG_ACT_USER_ACTION_1) || (menuEntryEvent.InternalEvent > InternalInterface.MG_ACT_USER_ACTION_20)) { internalEventMenuEnabled = true; } } bool refresh; if (menuValue.IsPulldown) { refresh = true; } else { refresh = false; } //set the ModalDisabled flag, depending upon the value of enable. if (!enable) { mnuEnt.setModalDisabled(false); } mnuEnt.setEnabled(enable, true, true, entryName, refresh); } if (internalEventMenuEnabled) { Manager.WriteToMessagePanebyMsgId(task, MsgInterface.MENU_STR_ERROR_ENABLE, false); } } return(true); }
public long GetTaskId(int taskIndex) { try { TaskBase task = _tasks.Tasks[taskIndex]; return(task.Id); } catch { return(Util.NullId); } }
/// <summary> /// This does not set a dependency between the two tasks. Instead, /// the Start method grabs the state of the previous task to pass on /// to the next task via previousSuccess and previousException /// </summary> /// <param name="handler"></param> internal void SetFaultHandler(TaskBase handler) { Task.ContinueWith(t => { Token.ThrowIfCancellationRequested(); handler.Start(t); }, Token, TaskContinuationOptions.OnlyOnFaulted, TaskManager.GetScheduler(handler.Affinity)); DependsOn?.SetFaultHandler(handler); }
protected void SetContinuation(TaskBase continuation, TaskContinuationOptions runOptions) { Token.ThrowIfCancellationRequested(); Task.ContinueWith(_ => { Token.ThrowIfCancellationRequested(); ((TaskBase)(object)continuation).Schedule(); }, Token, runOptions, TaskManager.GetScheduler(continuation.Affinity)); }
public static void Schedule(TaskBase task, uint initialDelay, uint retryDelay, uint retry) { if (_timer != null || _task != null) { // The class is currently only called once per process... Logger.LogError("The task and timer is will be overwritten by the new event. This class assumes it will be unique per process."); } _task = task; _retryDelay = retryDelay; _retry = retry; Wait(initialDelay); }
/// <summary> /// TaskFactory类可以开启后台工作线程,当A线程工作完成后,可指定B线程为后续工作 /// 本类中,当UI发起的任务结束后,会调用TaskBase类的委托,用以刷新数据或更新界面,即后台线程与UI通信。 /// </summary> /// <param name="task">需要执行的任务,用户可定制任务类,必须继承ITask接口</param> /// <param name="scheduler">此处实现单例模式,当用户需要开启一个任务时,需要指定该任务的上下文,从而在线程中获取更新UI的能力</param> public static void AddTask(TaskBase task, TaskScheduler scheduler) { if (_mainUiScheduler == null) _mainUiScheduler = scheduler; ProgressForm form = new ProgressForm(); form.Show(); TaskFactory taskFactory = new TaskFactory(); Task A = taskFactory.StartNew(task.Run); Task B = A.ContinueWith(t => { task.UpdateDataByDelegate(); form.Close(); }, _mainUiScheduler); }
public async Task<WebTaskResult> StartAsync(TaskBase task) { task.SendMessage = this.SendMessage; MusicRepository.SetName(task); task.Logger = LoggerFactory.CreateLogger(task.Name); task.Options = this.Options; WebTaskResult result = await Start(task, (wtr) => { }); if (!result.Success && result.IsRunning) { Logger.LogWarning($"Task {task.Name} is already running"); } return result; }
/// <summary> /// Добавление задачи в очередь с отметкой времени добавления /// </summary> /// <param name="list"></param> /// <param name="val"></param> public static void AddTask(this List<TaskBase> list, TaskBase val) { val.PushQueueTime = Program.ModelingTime; list.Add(val); }
public void StartAndForget(TaskBase task, bool longRunning = false) { Task.Run(() => { StartAsync(task).ConfigureAwait(false); }); }
/// <summary> /// /// </summary> /// <param name="taskBase"></param> public override void SaveTaskBaseAsConcreteTask( TaskBase taskBase ) { Data.SaveObject<TaskXmlModify>( taskBase as TaskXmlModify ); }
public override void Execute( TaskBase task ) { TaskXmlModify taskXmlModifyOriginal = task as TaskXmlModify; TaskXmlModify taskXmlModify = GetTaskXmlModifyWithCustomVariablesResolved(taskXmlModifyOriginal); // Store this error to use when throwing exceptions. string taskDetails = string.Format( CultureInfo.CurrentCulture, "Task ID : {0}\r\n" + "Task Description : {1}\r\n" + "XML File : {2}\r\n" + "Node to Change : {3}\r\n" + "Attribute Key : {4}\r\n" + "Attribute Key Value : {5}\r\n" + "Attribute to Change : {6}\r\n" + "Attribute to Change Value: {7}\r\n", taskXmlModify.TaskItemId, taskXmlModify.Description, taskXmlModify.XmlPathAndFileName, taskXmlModify.NodeToChange, taskXmlModify.AttributeKey, taskXmlModify.AttributeKeyValue, taskXmlModify.AttributeToChange, taskXmlModify.AttributeToChangeValue ); try { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(taskXmlModify.XmlPathAndFileName); XmlElement rootElement = xmlDocument.DocumentElement; XmlNodeList xmlNodes; // Get the node that the user wants to modify if( string.IsNullOrEmpty( taskXmlModify.AttributeKey.Trim() ) ) { // No attributes necessary to differentiate this node from any others. Get the matching nodes. xmlNodes = rootElement.SelectNodes( taskXmlModify.NodeToChange ); } else { // Get the nodes with the specified attributes xmlNodes = rootElement.SelectNodes( string.Format( CultureInfo.InvariantCulture, "descendant::{0}[@{1}='{2}']", taskXmlModify.NodeToChange, taskXmlModify.AttributeKey, taskXmlModify.AttributeKeyValue ) ); } if( xmlNodes == null ) { // If this is happening, see the comments section below for a possible reason: // -- xmlnode not found because of namespace attribute -- throw new Exception( "xmlNode not found.\r\n" /* + taskDetails */ ); } // Make the change foreach( XmlNode xmlNode in xmlNodes ) { if( string.IsNullOrEmpty( taskXmlModify.AttributeToChange ) ) { // We're not changing an attribute of the node; we're changing the value (InnerText) of the node itself. xmlNode.InnerText = taskXmlModify.AttributeToChangeValue; } else { if( xmlNode.Attributes[ taskXmlModify.AttributeToChange ] == null ) { throw new Exception( "Can't update Attribute to Change because it does not exist in the file." ); } // The node has an attribute, so change the attribute's value. xmlNode.Attributes[ taskXmlModify.AttributeToChange ].Value = taskXmlModify.AttributeToChangeValue; } } xmlDocument.Save(taskXmlModify.XmlPathAndFileName); xmlDocument = null; taskXmlModifyOriginal.TaskSucceeded = true; Utility.Log( taskDetails ); } catch( Exception ex ) { taskXmlModifyOriginal.TaskSucceeded = false; Utility.ProcessException( ex.Message + "\r\n" + taskDetails, ex, true ); } finally { Utility.Log( taskDetails ); } }
public static void TaskProgressing(TaskBase task) { try { } catch (Exception exc) { ErrorLogger.SchedulerProcessException(exc); } }
public static void TaskStarted(TaskBase task) { bool ActiveThreadCountIncremented = false; try { task.TaskRecordItem.ThreadID = Thread.CurrentThread.GetHashCode(); if (task.TaskRecordItem.Status != true) task.TaskRecordItem.Status = false; task.TaskRecordItem.ReturnText = "Process Started"; IPHostEntry entries = Dns.GetHostEntry(Dns.GetHostName()); task.TaskRecordItem.Server = entries.AddressList[0].ToString(); RemoveFromScheduleQueue(task.TaskRecordItem); AddToScheduleInProgress(task.TaskRecordItem); Interlocked.Increment(ref ActiveThreadCount); ActiveThreadCountIncremented = true; task.TaskRecordItem.HistoryStartDate = DateTime.Now; task.TaskRecordItem.ScheduleHistoryID = SchedulerController.AddTaskHistory(task.TaskRecordItem); } catch (Exception exc) { if (ActiveThreadCountIncremented) Interlocked.Decrement(ref ActiveThreadCount); if (task.TaskRecordItem != null) ErrorLogger.SchedulerProcessException(exc); } }
public override void Execute( TaskBase task ) { TaskMsi taskMsi = task as TaskMsi; try { Process process = new Process(); string arguments; process.StartInfo.FileName = "msiexec"; string targetSiteParameter = taskMsi.IisWebSite.Length > 0 ? " TARGETSITE=" + taskMsi.IisWebSite : string.Empty; string passiveParameter = taskMsi.PassiveInstall == 1 ? " /passive" : string.Empty; string targetDirParameter = taskMsi.InstallationLocation.Length > 0 ? " TARGETDIR=\"" + taskMsi.InstallationLocation + "\"" : string.Empty; if( taskMsi.Install == 1 ) { // Install arguments = "/i " + taskMsi.Path + "\\" + taskMsi.FileName + targetSiteParameter + passiveParameter + targetDirParameter; } else { // Uninstall arguments = "/uninstall " + taskMsi.ProductGuid + passiveParameter; } process.StartInfo.Arguments = Utility.ReplaceVariablesWithValues( arguments, task.TaskGroupId ); process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardOutput = true; process.Start(); string processOutput = process.StandardOutput.ReadToEnd(); process.WaitForExit(); Utility.Log( string.Format( CultureInfo.CurrentCulture, "Task Description: {0}\r\n" + "Command : {1} {2}\r\n" + "Process Output : {3}", taskMsi.Description, process.StartInfo.FileName, process.StartInfo.Arguments, processOutput ) ); if( process.ExitCode != 0 ) { throw new Exception( string.Format( CultureInfo.CurrentCulture, "TaskMSI failed with an exit code of {0}.", process.ExitCode.ToString( CultureInfo.CurrentCulture ) ) ); } taskMsi.TaskSucceeded = true; } catch( Exception ex ) { taskMsi.TaskSucceeded = false; Utility.ProcessException( string.Empty, ex, true ); } finally { Utility.Log( "Task MSI\r\n" + "Task Desc : " + task.Description + "\r\n" + "TaskID : " + task.TaskItemId + "\r\n" + "Product GUID : " + taskMsi.ProductGuid + "\r\n" + "Path : " + taskMsi.Path + "\r\n" + "Install Loc : " + taskMsi.InstallationLocation + "\r\n" + "File Name : " + taskMsi.FileName + "\r\n" + "Result : " + ( taskMsi.TaskSucceeded == true ? "Succeeded" : "Failed" ) ); } }
/// <summary> /// /// </summary> /// <param name="taskBase"></param> public override void SaveTaskBaseAsConcreteTask( TaskBase taskBase ) { Data.SaveObject<TaskMsi>( taskBase as TaskMsi ); }
public static void TaskErrored(TaskBase task, Exception exception) { try { ScheduleHistory objScheduleHistoryItem = task.TaskRecordItem; RemoveFromScheduleInProgress(objScheduleHistoryItem); Interlocked.Decrement(ref ActiveThreadCount); objScheduleHistoryItem.HistoryEndDate = DateTime.Now; DateTime startedTime = objScheduleHistoryItem.HistoryStartDate ?? DateTime.Now; if (objScheduleHistoryItem.RetryTimeLapse > 0) { switch (objScheduleHistoryItem.RetryFrequencyUnit) { case 1: startedTime.AddSeconds(objScheduleHistoryItem.RetryTimeLapse); break; case 2: startedTime.AddMinutes(objScheduleHistoryItem.RetryTimeLapse); break; case 3: startedTime.AddHours(objScheduleHistoryItem.RetryTimeLapse); break; case 4: startedTime.AddDays(objScheduleHistoryItem.RetryTimeLapse); break; } objScheduleHistoryItem.NextStart = Convert.ToString(startedTime); } objScheduleHistoryItem.Status = false; string error = ""; StringBuilder errorlog = new StringBuilder(); errorlog.AppendLine("Error"); if ((exception != null)) { error = exception.Message; } errorlog.AppendLine(error); task.TaskRecordItem.ReturnText = errorlog.ToString(); SchedulerController.UpdateTaskHistory(objScheduleHistoryItem); if (!string.IsNullOrEmpty(objScheduleHistoryItem.NextStart) && objScheduleHistoryItem.RetryTimeLapse > 0) { objScheduleHistoryItem.HistoryStartDate = null; objScheduleHistoryItem.HistoryEndDate = null; objScheduleHistoryItem.ReturnText = ""; objScheduleHistoryItem.ProcessGroup = -1; AddToScheduleQueue(objScheduleHistoryItem); } } catch (Exception exc) { if (task.TaskRecordItem != null) ErrorLogger.SchedulerProcessException(exc); } }
/// <summary> /// Занять канал задачей /// </summary> /// <param name="task"></param> /// <param name="channelNum"></param> public void Seize(TaskBase task, int channelNum) { switch (channelNum) { case Channels.Channel1: Channel1.CurrentTask = task; Channel1.IsAvailable = false; break; case Channels.Channel2: Channel2.CurrentTask = task; Channel2.IsAvailable = false; break; case Channels.AllChannels: if (task.Type != TaskTypes.ClassC) throw new ArgumentException("Задача не может занимать оба канала одновременно" + Name); Channel1.CurrentTask = task; Channel1.IsAvailable = false; Channel2.CurrentTask = task; Channel2.IsAvailable = false; break; default: throw new ArgumentException("Недопустимый номер канала для устройства" + Name); } }
public static void TaskCompleted(TaskBase task) { try { ScheduleHistory objScheduleHistory = task.TaskRecordItem; objScheduleHistory = task.TaskRecordItem; RemoveFromScheduleInProgress(objScheduleHistory); Interlocked.Decrement(ref ActiveThreadCount); objScheduleHistory.HistoryEndDate = DateTime.Now; objScheduleHistory.Status = true; objScheduleHistory.NextStart = SchedulerController.GetNextStart(objScheduleHistory); task.TaskRecordItem.ReturnText = "Successfully completed"; SchedulerController.UpdateTaskHistory(objScheduleHistory); if (!string.IsNullOrEmpty(objScheduleHistory.NextStart)) { objScheduleHistory.HistoryStartDate = null; objScheduleHistory.HistoryEndDate = null; objScheduleHistory.ReturnText = ""; objScheduleHistory.ProcessGroup = -1; objScheduleHistory.Status = false; AddToScheduleQueue(objScheduleHistory); } } catch (Exception exc) { if (task.TaskRecordItem != null) ErrorLogger.SchedulerProcessException(exc); } }
/// <summary> /// Gets an instance of a logic class based on its type. /// </summary> /// <param name="task"><see cref="TaskBase"/></param> /// <returns>Logic class intance, for example: TaskXmlModifyLogic.</returns> private TaskBaseLogic GetTaskLogicClassOfSelectedTask( TaskBase task ) { TaskType taskType = TaskTypeLogic.GetById( task.TaskTypeId ); // Note: Need ", PrestoCore" below because we're activating a type in another assembly. string className = "PrestoCore.BusinessLogic.BusinessComponents." + taskType.Description + "Logic, PrestoCore"; return Activator.CreateInstance( Type.GetType( className ) ) as TaskBaseLogic; }
/// <summary> /// 任务开始运行 /// </summary> /// <param name="task">任务基类</param> public void Start(TaskBase task) { if (task == null) return; //如果任务为空则返回 if (!CheckTaskRunState(TaskRunState.Starting)) //是否可以进入启动状态 { Logger.Error("无法启动,当前任务“{0}”状态:{1}".FormatWith(_task.Name,TaskRunState.ToString())); return; } _task = task; //否则当前任务等于task _taskEventArg = new TaskEventArg{ Context=task.Context}; Window = task.Context.Role.Window; //当前窗口等于当前角色所在窗口 if (_workThread == null) //没有在执行任务,则获取任务线程 { _workThread = GetWorkThread(); //获取任务线程 } Logger.Debug(string.Format("任务“{0}”正在启动...",_task.Name)); TaskRunState = TaskRunState.Starting; //任务状态改为正在启动 DoEventHandler(OnStateChanged,_taskEventArg); DoEventHandler(OnStarting,_taskEventArg); _workThread.Start(); //线程启动 }
public void EnqueueTask(TaskBase task) { lock (QueuedTasks) { QueuedTasks.Add(task); } }
private void SaveAsConcreteTask( TaskBase taskBase ) { TaskType taskType = TaskTypeLogic.GetById( taskBase.TaskTypeId ); string assemblyQualifiedClassName = "PrestoCore.BusinessLogic.BusinessComponents." + taskType.Description + "Logic, PrestoCore"; TaskBaseLogic taskBaseLogic = Activator.CreateInstance( Type.GetType( assemblyQualifiedClassName, true, true ) ) as TaskBaseLogic; taskBaseLogic.SaveTaskBaseAsConcreteTask( taskBase ); }