private void RunSelfTaskAndUpdateAction() { string user = HttpContext.Current.User.Identity.Name.Replace(@"ANALIT\", string.Empty); var thisTask = ScheduleHelper.GetTaskOrCreate(taskService, reportsFolder, Convert.ToUInt64(_generalReport.Id), user, "temp_"); var newAction = new ExecAction(ScheduleHelper.ScheduleAppPath, "/gr:" + _generalReport.Id + string.Format(" /inter:true /dtFrom:{0} /dtTo:{1} /manual:true", DateTime.Parse(dtFrom.Value).ToShortDateString(), DateTime.Parse(dtTo.Value).ToShortDateString()), ScheduleHelper.ScheduleWorkDir); var taskDefinition = thisTask.Definition; taskDefinition.Actions.RemoveAt(0); taskDefinition.Actions.Add(newAction); taskDefinition.RegistrationInfo.Description = user; taskDefinition.Settings.RunOnlyIfIdle = false; taskDefinition.Settings.StopIfGoingOnBatteries = false; taskDefinition.Settings.DisallowStartIfOnBatteries = false; taskDefinition.Settings.StopIfGoingOnBatteries = false; ScheduleHelper.UpdateTaskDefinition(taskService, reportsFolder, Convert.ToUInt64(_generalReport.Id), taskDefinition, "temp_"); if (thisTask.State != TaskState.Running) { thisTask.Run(); Session.Add("StartTaskTime", DateTime.Now); Response.Redirect("Schedule.aspx?r=" + _generalReport.Id); } }
private ScheduledProgram ScheduledProgramFromTask(Task task) { WeeklyTrigger trigger = task.Definition.Triggers.Where(trig => trig is WeeklyTrigger).Cast <WeeklyTrigger>().FirstOrDefault(); ExecAction action = task.Definition.Actions.Where(a => a is ExecAction).Cast <ExecAction>().FirstOrDefault(); if (trigger == null || action == null) { return(null); } ScheduledProgram program = new ScheduledProgram(); if (task.Name.StartsWith("Comet\\")) { program.name = task.Name.Substring("Comet\\".Length); } else { program.name = task.Name; } program.weekDays = trigger.DaysOfWeek; program.startTime = trigger.StartBoundary.TimeOfDay; program.endTime = trigger.EndBoundary.TimeOfDay; program.firstDate = trigger.StartBoundary.Date; program.lastDate = trigger.EndBoundary.Date; CommandLineOptions options = AutoPlay.ParseCommandLine(action.Arguments); program.sequences = options.Sequences.ToList(); program.endTime = program.startTime.Add(TimeSpan.FromMinutes(options.Minutes)); return(program); }
public void RegisterTask(TaskService taskService) { TaskDefinition def = taskService.NewTask(); string applicationExe = Application.ExecutablePath; string arguments = GetCommandLine(); WeeklyTrigger trigger = new WeeklyTrigger(weekDays, 1); trigger.StartBoundary = firstDate.Date + startTime; if (endTime > startTime) { trigger.EndBoundary = lastDate.Date + endTime; } else { trigger.EndBoundary = lastDate.Date.AddDays(1) + endTime; } ExecAction action = new ExecAction(applicationExe, arguments, Path.GetDirectoryName(applicationExe)); def.Triggers.Add(trigger); def.Actions.Add(action); def.Principal.LogonType = TaskLogonType.InteractiveToken; def.RegistrationInfo.Description = "Comet Lighting Program\r\n\r\n" + string.Join("", sequences.Select(s => " " + Path.GetFileName(s) + "\r\n")); def.Settings.WakeToRun = true; def.Settings.DisallowStartIfOnBatteries = false; def.Settings.StopIfGoingOnBatteries = false; def.Settings.RunOnlyIfIdle = false; def.Settings.IdleSettings.StopOnIdleEnd = false; def.Settings.DeleteExpiredTaskAfter = TimeSpan.FromHours(12); taskService.RootFolder.RegisterTaskDefinition("Comet\\" + name, def); }
public static bool CreateTask(string ComputerName) { bool success = false; try { using (TaskService ts = new TaskService(Properties.Resources.CBTaskServer)) { TaskDefinition td = ts.NewTask(); td.RegistrationInfo.Description = string.Format("CB Install for {0}", ComputerName); td.Principal.LogonType = TaskLogonType.Password; TimeTrigger tt = new TimeTrigger(); tt.Enabled = true; tt.StartBoundary = DateTime.Today + TimeSpan.FromHours(23); //tt.EndBoundary = DateTime.Today + TimeSpan.FromDays(2); tt.Repetition.Interval = TimeSpan.FromMinutes(60); tt.Repetition.StopAtDurationEnd = true; tt.Repetition.Duration = TimeSpan.FromDays(1); td.Triggers.Add(tt); ExecAction ea1 = new ExecAction(); ea1.Path = @"C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe"; ea1.Arguments = Properties.Resources.CBPSScriptPathandName + " " + ComputerName; td.Actions.Add(ea1); string taskName = "CBInstall " + ComputerName; ts.RootFolder.RegisterTaskDefinition(taskName, td, TaskCreation.CreateOrUpdate, Properties.Resources.CBserviceAccount, Properties.Resources.CBSApwd); success = true; } } catch { } return(success); }
/// <summary> /// 创建windows计划任务 /// </summary> /// <param name="taskName">任务名称</param> /// <param name="stateTime">执行时间</param> public static void CreateTask(string taskName, DateTime stateTime) { try { // 计划任务服务 TaskService ts = new TaskService(); // 创建一个计划任务 TaskDefinition td = ts.NewTask(); td.RegistrationInfo.Description = "DTU执行未执行过的任务"; //任务描述 td.RegistrationInfo.Author = "EcpDtu"; //任务作者 //时间执行时间 TimeTrigger tt = new TimeTrigger(); tt.StartBoundary = DateTime.Now.AddSeconds(5); //stateTime.AddHours(4); //开始时间 tt.EndBoundary = DateTime.Now.AddSeconds(10); //stateTime.AddHours(8); //结束执行时间 td.Triggers.Add(tt); //将触发器添加到任务中 //创建一个执行操作 var exe = new ExecAction("RunTask.exe", null, System.Configuration.ConfigurationSettings.AppSettings["RunTask_path"]); //添加执行操作到计划任务的操作中 td.Actions.Add(exe); //注册计划任务 ts.RootFolder.RegisterTaskDefinition(taskName, td); } catch (Exception ex) { MessageBox.Show("创建计划任务错误_CreateTask(string name)" + ex.Message); } }
public void Dev2ActionCollection_Enumerate() { var collection = new Dev2ActionCollection(_taskServiceConvertorFactory.Object, _nativeInstance); var nativeAction = new ExecAction("a", "b", "c"); var actionToAdd = new Dev2ExecAction(_taskServiceConvertorFactory.Object, nativeAction); _taskServiceConvertorFactory.Setup(a => a.CreateAction(nativeAction)).Returns(actionToAdd); collection.Add(actionToAdd); var nativeAction1 = new ExecAction("1", "2", "3"); var nativeAction2 = new ExecAction("4", "6", "4"); var actionToAdd1 = new Dev2ExecAction(_taskServiceConvertorFactory.Object, nativeAction1); var actionToAdd2 = new Dev2ExecAction(_taskServiceConvertorFactory.Object, nativeAction2); _taskServiceConvertorFactory.Setup(a => a.CreateAction(It.IsAny <ExecAction>())).Returns(actionToAdd); collection.Add(actionToAdd1); collection.Add(actionToAdd2); var e = collection.GetEnumerator(); Assert.IsTrue(e.MoveNext()); Assert.AreEqual(((ExecAction)e.Current.Instance).Path, "a"); _taskServiceConvertorFactory.Setup(a => a.CreateAction(It.IsAny <ExecAction>())).Returns(actionToAdd1); Assert.IsTrue(e.MoveNext()); Assert.AreEqual(((ExecAction)e.Current.Instance).Path, "1"); _taskServiceConvertorFactory.Setup(a => a.CreateAction(It.IsAny <ExecAction>())).Returns(actionToAdd2); Assert.IsTrue(e.MoveNext()); Assert.AreEqual(((ExecAction)e.Current.Instance).Path, "4"); Assert.IsFalse(e.MoveNext()); }
static void SetStartup(bool add) { var service = TaskService.Instance; var existingTask = service.GetTask(TaskName); if (existingTask != null) { service.RootFolder.DeleteTask(TaskName); } if (add) { var file = new FileInfo(Application.ExecutablePath); var action = new ExecAction(); action.Path = file.FullName; action.WorkingDirectory = file.Directory.FullName; var task = service.NewTask(); task.Actions.Add(action); task.Triggers.Add(new LogonTrigger()); service.RootFolder.RegisterTaskDefinition(TaskName, task); } }
private bool TestLogon(string user, string pw) { bool result = false; try { using (TaskService ts = new TaskService()) { TaskDefinition td = ts.NewTask(); string exePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Autodesk\Revit\Addins\2014\HOK-BatchProcessor.bundle\Contents\HOK.BatchExportTrigger.exe"; ExecAction execAction = new ExecAction(exePath, null, null); td.Actions.Add(execAction); Task task = ts.RootFolder.RegisterTaskDefinition(@"Test", td, TaskCreation.CreateOrUpdate, user, pw, TaskLogonType.InteractiveTokenOrPassword); if (null != task) { ts.RootFolder.DeleteTask("Test"); return(true); } } } catch { passwordBox.Clear(); labelMessage.Visibility = Visibility.Visible; return(false); } return(result); }
private void UpdateAutoStartTaskPath() { using (TaskService taskService = new TaskService()) { Task task = taskService.GetTask(GetAutoStartTaskName()); if (task != null) { ExecAction action = (ExecAction)task.Definition.Actions.Single(); bool isTaskScheduler2OrLater = taskService.HighestSupportedVersion.Minor >= 2; if (!PathHelper.ArePathsEqual(action.Path, Application.ExecutablePath) || (isTaskScheduler2OrLater && !PathHelper.ArePathsEqual(action.WorkingDirectory, WinFormsHelper.ExecutableDirectory))) { if (isTaskScheduler2OrLater) { action.Path = Application.ExecutablePath; action.WorkingDirectory = WinFormsHelper.ExecutableDirectory; task.RegisterChanges(); } else { DeleteAutoStartTask(taskService); CreateAutoStartTask(taskService); } Logger.Instance.Log(LogLevel.Warning, "Updated path of executable in auto-start task in TaskScheduler."); } } } }
private string GetCommandText(Action action) { ExecAction execAction = action as ExecAction; ShowMessageAction showMessageAction = action as ShowMessageAction; ComHandlerAction comHandlerAction = action as ComHandlerAction; EmailAction emailAction = action as EmailAction; if (execAction != null) { return($"{execAction.Path} {execAction.Arguments}"); } else if (showMessageAction != null) { return($"Show message: '{showMessageAction.Title}'"); } else if (comHandlerAction != null) { return($"COM handler: '{comHandlerAction.ClassName}'"); } else if (emailAction != null) { return($"Send email: '{emailAction.Subject}'"); } else { return("unknown action."); } }
private void createSchTask(string name, string arg) { if (string.IsNullOrWhiteSpace(fileLocationTextBox.Text)) { MessageBox.Show("Please, select a file.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } else { Task tsk = null; string fileLocation = fileLocationTextBox.Text; using (TaskService ts = new TaskService()) { TaskDefinition td = ts.NewTask(); td.Principal.RunLevel = TaskRunLevel.Highest; td.RegistrationInfo.Description = "Runs a command-line file with " + arg + " argument."; td.Settings.DisallowStartIfOnBatteries = false; ExecAction ex = td.Actions.Add(new ExecAction(fileLocation, arg, null)); tsk = ts.RootFolder.RegisterTaskDefinition(name, td, TaskCreation.CreateOrUpdate, "SYSTEM", null, TaskLogonType.ServiceAccount); tsk.Run(); } taskRunActions(tsk); } }
public bool ValidateFields() { // Check to ensure Path is a valid filename if (ExecAction.IsValidPath(execProgText.Text)) { return(true); } MessageBox.Show(this, EditorProperties.Resources.Error_InvalidFileName, null, MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); }
Dev2ActionCollection CreateCollection() { var collection = new Dev2ActionCollection(_taskServiceConvertorFactory.Object, _nativeInstance); var nativeAction = new ExecAction("a", "b", "c"); var actionToAdd = new Dev2ExecAction(_taskServiceConvertorFactory.Object, nativeAction); _taskServiceConvertorFactory.Setup(a => a.CreateAction(nativeAction)).Returns(actionToAdd); collection.Add(actionToAdd); return(collection); }
public void DefineAction(string AppPath, string args = "") { ExecAction action = new ExecAction(AppPath, args); def.Actions.Add(action); def.Principal.RunLevel = TaskRunLevel.Highest; def.Settings.Priority = System.Diagnostics.ProcessPriorityClass.BelowNormal; //def.Settings.RunOnlyIfLoggedOn = false; }
private bool recordJob()//JobEditor frmJob) { //record configuration _job.Config.TaskPassword = txtPassword.Text; _job.Config.TaskUser = txtUser.Text; try { //add task to windows scheduler using (TaskService mgr = new TaskService()) { if (!mgr.RootFolder.SubFolders.Exists("Duplicate File")) { mgr.RootFolder.CreateFolder("Duplicate File"); } TaskDefinition td = mgr.NewTask(); td.RegistrationInfo.Description = "Duplicate file job"; Trigger trigger; if (chkPeriodicaly.Checked) { trigger = SchedulerTrigger.getTrigger(cmbFrequency.SelectedIndex); trigger.StartBoundary = dtpHour.Value; } else { trigger = SchedulerTrigger.getTrigger((int)SchedulerTrigger.TriggerTypes.OneTime); trigger.StartBoundary = dtpOneTime.Value; } td.Triggers.Add(trigger); var action = new ExecAction() { Path = "duplicateFile.exe", WorkingDirectory = Config.DefaultPath, Arguments = _job.Id.ToString() }; td.Actions.Add(action); var task = mgr.RootFolder.RegisterTaskDefinition("\\Duplicate File\\" + _job.Id, td, TaskCreation.CreateOrUpdate, _job.Config.TaskUser, _job.Config.TaskPassword, TaskLogonType.Password); } } catch (Exception ex) { MessageBox.Show(Resources.Languages.Resources.Error_Creation_tache, Resources.Languages.Resources.Erreur, MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } _job.Config.Save(Config.DefaultJobPath + _job.Id + ".conf"); return(true); }
public OperationResponse ItemOperationExecAction(MmoItem item, ExecAction operation, MmoActor actor) { if (item.Owner == null) { return new OperationResponse((byte)OperationCode.ExecAction) { ReturnCode = (int)ReturnCode.Fatal, DebugMessage = "Item owner is null in ExecAction" } } ; object[] parameters = operation.Parameters; if (operation.Action == "CreateRaider" || operation.Action == "DestroyAnyRaider") { ArrayList arrLst = new ArrayList(parameters); arrLst.Insert(0, actor.World); parameters = arrLst.ToArray(); } var method = item.Owner.ActionExecutor.GetType().GetMethod(operation.Action); Hashtable result = null; if (method != null) { object respObject = method.Invoke(item.Owner.ActionExecutor, parameters); if (respObject != null && respObject is Hashtable) { result = respObject as Hashtable; } } else { return(new OperationResponse((byte)OperationCode.ExecAction, new ExecActionResponse { Action = operation.Action, ItemId = string.Empty, Result = new Hashtable() }) { ReturnCode = (short)ReturnCode.Fatal, DebugMessage = string.Format("Method: {0} not founded in ExecAction", operation.Action) }); } operation.OnComplete(); if (result == null) { result = new Hashtable(); } ExecActionResponse response = new ExecActionResponse { Result = result, Action = operation.Action, ItemId = item.Id }; return(new OperationResponse((byte)OperationCode.ExecAction, response) { ReturnCode = (int)ReturnCode.Ok, DebugMessage = string.Format("action: {0} completed", operation.Action) }); } }
public void TaskShedulerWrapper_Dev2Action_Construct() { using (Microsoft.Win32.TaskScheduler.Action act = new ExecAction("bob", "dave", "jane")) { var wrapped = new Dev2Action(act); wrapped.Id = Guid.NewGuid().ToString(); Assert.AreEqual(act.ActionType, wrapped.ActionType); Assert.AreEqual(act.Id, wrapped.Id); Assert.AreEqual(act, wrapped.Instance); } }
public static void CreateOrUpdateTask() { try { const string description = "PersianBingCalendar Runner"; var execAction = new ExecAction(Application.ExecutablePath, null, Application.StartupPath); using (var task = TaskService.Instance.NewTask()) { var isVesrion2 = TaskService.Instance.HighestSupportedVersion >= new Version(1, 2); task.RegistrationInfo.Description = description; task.RegistrationInfo.Author = "DNT"; task.Settings.Hidden = true; // Project -> Properties -> Application tab -> Output type -> `Windows Application` task.Settings.Enabled = true; task.Settings.DisallowStartIfOnBatteries = false; task.Settings.StopIfGoingOnBatteries = false; if (isVesrion2) { task.Settings.StartWhenAvailable = true; task.Settings.MultipleInstances = TaskInstancesPolicy.IgnoreNew; } var trigger1 = createHourlyTrigger(); if (!isVesrion2) { trigger1.Repetition.Duration = TimeSpan.FromHours(1.1); } task.Triggers.Add(trigger1); var trigger2 = createDailyStartTrigger(); if (!isVesrion2) { trigger2.Repetition.Duration = TimeSpan.FromHours(1.1); } task.Triggers.Add(trigger2); task.Actions.Add(execAction); TaskService.Instance.RootFolder.RegisterTaskDefinition( description, task, TaskCreation.CreateOrUpdate, null, null, TaskLogonType.InteractiveToken, null); } Console.WriteLine($"`{description}` task has been added."); } catch (Exception ex) { ex.LogException(); } }
/// <summary> /// 创建一个以指定日期时间为触发条件的计划任务 /// </summary> /// <param name="subFolderName">计划任务所在的文件夹</param> /// <param name="taskName">计划任务的名称</param> /// <param name="taskDescription">计划任务描述</param> /// <param name="path">应用程序路径</param> /// <param name="startBoundary">指定日期时间</param> /// <param name="arguments">应用程序参数</param> /// ///using语句,定义一个范围,在范围结束时处理对象。 场景: ///当在某个代码段中使用了类的实例,而希望无论因为什么原因,只要离开了这个代码段就自动调用这个类实例的Dispose。 ///要达到这样的目的,用try...catch来捕捉异常也是可以的,但用using也很方便。 public static void CreateOnceRunTask(string subFolderName, string taskName, string taskDescription, string path, DateTime startBoundary, string arguments) { //以指定日期時間为触发时间初始化触发器 using (TimeTrigger trigger = new TimeTrigger(startBoundary)) { ///初始化执行任务的应用程序 using (ExecAction action = new ExecAction(path, arguments, null)) { CreateTask(subFolderName, taskName, taskDescription, trigger, action); } } }
public void Init() { _taskService = new TaskService(); var newTask = _taskService.NewTask(); var action = new ExecAction("bob.exe"); newTask.Actions.Add(action); newTask.Triggers.Add(new DailyTrigger()); _taskService.RootFolder.RegisterTaskDefinition("UnitTestTask", newTask); _factory = new Mock <ITaskServiceConvertorFactory>(); }
public TimedTask(string deviceId, int portNumber, bool enabled, string taskId, ExecType execType, ExecAction execAction, int executed, LoopType loopType, Moment moment, string loopMonent) : this() { DeviceId = deviceId; PortNumber = portNumber; Enabled = enabled; TaskId = taskId; ExecType = execType; ExecAction = execAction; Executed = executed;//未执行 执行中 已执行 LoopType = loopType; Moment = moment; LoopMonent = loopMonent; }
public void AddOrUpdate(AddOrUpdateOptions addOrUpdateOptions) { try { string name = addOrUpdateOptions.Name; string description = addOrUpdateOptions.Description; if (string.IsNullOrEmpty(name)) { name = "Run " + addOrUpdateOptions.Command; } if (string.IsNullOrEmpty(description)) { description = "Run " + addOrUpdateOptions.Command; } using (TaskService service = new TaskService()) { bool exists = service.AllTasks.Any(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)); Trigger[] triggers = Trigger.FromCronFormat(addOrUpdateOptions.Expression); // doesn't support "*/5" for minutes/hours yet. string workingDirectory = addOrUpdateOptions.WorkingDirectory ?? Path.GetDirectoryName(addOrUpdateOptions.Command); var action = new ExecAction(addOrUpdateOptions.Command, addOrUpdateOptions.Arguments, workingDirectory); TaskDefinition taskDefinition = service.NewTask(); taskDefinition.Principal.RunLevel = TaskRunLevel.Highest; taskDefinition.Principal.LogonType = TaskLogonType.InteractiveTokenOrPassword; taskDefinition.RegistrationInfo.Description = description; taskDefinition.Triggers.AddRange(triggers); taskDefinition.Actions.Add(action); service.RootFolder.RegisterTaskDefinition(name, taskDefinition); string outputStatusText = (exists) ? "updated" : "created"; Helper.WriteConsoleColor($"'{name}' {outputStatusText}:", ConsoleColor.Green); Console.WriteLine(); Console.WriteLine(ExpressionDescriptor.GetDescription(addOrUpdateOptions.Expression)); } } catch (Exception ex) { Helper.WriteConsoleColor("An error occurred: " + ex, ConsoleColor.Red); Console.WriteLine(); } }
public ScheduledTaskDetails GetScheduledTaskDetails(string machineName, string taskName) { Guard.NotNullNorEmpty(machineName, "machineName"); Guard.NotNullNorEmpty(taskName, "taskName"); using (var taskService = CreateTaskService(machineName)) { Task task = taskService.FindTask(taskName, false); if (task == null) { return(null); } ExecAction action = (ExecAction)task.Definition.Actions .Single(x => x is ExecAction); string execPath = action.Path; DailyTrigger trigger = (DailyTrigger)task.Definition.Triggers .Single(); int startHour = trigger.StartBoundary.Hour; int startMinute = trigger.StartBoundary.Minute; int executionTimeLimits = (int)trigger.ExecutionTimeLimit.TotalMinutes; var repetition = new ScheduledTaskRepetition( trigger.Repetition.Interval, trigger.Repetition.Duration, trigger.Repetition.StopAtDurationEnd); return (new ScheduledTaskDetails( task.Name, task.Enabled, task.State == TaskState.Running, task.LastRunTime, task.NextRunTime, execPath, startHour, startMinute, executionTimeLimits, repetition)); } }
public static Task CreateTemporaryTaskForRunFromInterface(TaskService service, TaskFolder folder, Task source, string action) { var task = ScheduleHelper.GetTaskOrCreate(service, folder, Convert.ToUInt64(1), "tempTask1", "temp"); var sourceDefinition = source.Definition; sourceDefinition.Triggers.Clear(); ScheduleHelper.UpdateTaskDefinition(service, folder, Convert.ToUInt64(1), sourceDefinition, "temp"); ScheduleHelper.SetTaskEnableStatus(1, true, "temp"); var definition = task.Definition; var newAction = new ExecAction(ScheduleHelper.ScheduleAppPath, action, ScheduleHelper.ScheduleWorkDir); definition.Actions.RemoveAt(0); definition.Actions.Add(newAction); ScheduleHelper.UpdateTaskDefinition(service, folder, Convert.ToUInt64(1), definition, "temp"); return(task); }
private static void ScheduleRegister(bool scheduleOn, double value) { var filename = Process.GetCurrentProcess().MainModule.FileName; using var action = new ExecAction(filename, null, Path.GetDirectoryName(filename)); using var taskDefinition = TaskService.Instance.NewTask(); taskDefinition.Settings.Enabled = scheduleOn; taskDefinition.Actions.Add(action); var trigger = new TimeTrigger { StartBoundary = DateTime.Today }; trigger.Repetition.Interval = TimeSpan.FromMinutes(value); taskDefinition.Triggers.Add(trigger); taskDefinition.Validate(true); TaskService.Instance.RootFolder.RegisterTaskDefinition(taskName, taskDefinition); }
private static void Project_AfterInstall(SetupEventArgs e) { string shortArch = e.Session.Property("ShortArch"); string longArch = e.Session.Property("LongArch"); string TaskName = $"VSCELicense{shortArch}"; if (e.IsInstalling) { TaskService ts = TaskService.Instance; TaskFolder tf = ts.RootFolder.CreateFolder(TaskSubFolderName, exceptionOnExists: false); TaskDefinition td = ts.NewTask(); ExecAction ea = new ExecAction(); ea.Path = "powershell.exe"; string PSCommand = @"Import-Module VSCELicense; Set-VSCELicenseExpirationDate"; ea.Arguments = $"-ExecutionPolicy Bypass -command \"{PSCommand}\""; td.Actions.Add(ea); td.Settings.StartWhenAvailable = true; td.Principal.LogonType = TaskLogonType.ServiceAccount; td.Principal.UserId = "SYSTEM"; td.Principal.RunLevel = TaskRunLevel.Highest; DailyTrigger dt = new DailyTrigger(); dt.StartBoundary = DateTime.Today + TimeSpan.FromHours(1); // 1am td.Triggers.Add(dt); tf.RegisterTaskDefinition(TaskName, td); } else if (e.IsUninstalling) { // Benefit fron elevation as here the order or file/task removal doesn't matter // but BeforeINstall event should have been used to remove the task before the files being deleted TaskService ts = TaskService.Instance; TaskFolder tf = ts.GetFolder(TaskSubFolderName); if (null != tf) { tf.DeleteTask(TaskName, false); int taskCount = tf.GetTasks().Count; if (0 == taskCount) { ts.RootFolder.DeleteFolder(TaskSubFolderName); } } } }
private OperationResponse ExecAction(PeerBase peer, OperationRequest request, SendParameters sendParameters) { try { var operation = new ExecAction(peer.Protocol, request); if (false == operation.IsValid) { return(GetErrorResponse(ReturnCode.InvalidOperationParameter, operation.GetErrorMessage())); } var method = this.executor.GetType().GetMethod(operation.Action); if (method != null) { object methodResult = method.Invoke(this.executor, operation.Parameters); if (methodResult != null && methodResult is Hashtable) { var hashResult = methodResult as Hashtable; ExecActionResponse response = new ExecActionResponse { Result = hashResult, Action = operation.Action, ItemId = string.Empty }; return(new OperationResponse(OperationCode.ExecAction.toByte(), response) { ReturnCode = (int)ReturnCode.Ok, DebugMessage = "action: {0} completed".f(operation.Action) }); } else { return(GetErrorResponse(ReturnCode.Fatal, "Invalid return value from method")); } } else { return(GetErrorResponse(ReturnCode.Fatal, "Method {0} in executor not founded".f(operation.Action))); } } catch (Exception ex) { CL.Out(LogFilter.PLAYER, ex.Message); CL.Out(LogFilter.PLAYER, ex.StackTrace); } return(null); }
static void AddTask(string computer, int hour, int min, string taskFolder, string taskName, string taskDescription, string actionPath, string actionArgs) { try { var taskService = new TaskService(); if (computer.ToUpper() != "LOCAL") { taskService = new TaskService(computer); } var taskDefinition = taskService.NewTask(); taskDefinition.RegistrationInfo.Description = taskDescription; taskDefinition.Principal.UserId = "SYSTEM"; var trigger = new DailyTrigger { StartBoundary = DateTime.Today + TimeSpan.FromHours(hour) + TimeSpan.FromMinutes(min) }; taskDefinition.Triggers.Add(trigger); var action = new ExecAction(actionPath, actionArgs); taskDefinition.Actions.Add(action); taskDefinition.Settings.Enabled = true; taskDefinition.Settings.Hidden = false; taskDefinition.Settings.WakeToRun = true; taskDefinition.Settings.AllowDemandStart = true; taskDefinition.Settings.StartWhenAvailable = true; taskDefinition.Settings.DisallowStartIfOnBatteries = false; taskDefinition.Settings.DisallowStartOnRemoteAppSession = false; taskDefinition.Settings.StopIfGoingOnBatteries = false; taskService.RootFolder.RegisterTaskDefinition(taskFolder + taskName, taskDefinition); taskService.FindTask(taskName).Run(); taskService.Dispose(); } catch (Exception e) { Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message); return; } }
} // SetAdditionalData private void SetAction(TaskDefinition definition, RecordTask record, string dbFile, string logFolder) { var arguments = new[] { "/Action:Record", $"/TaskId:{record.TaskId}", $"/Database:{dbFile}", $"/LogFolder:{logFolder}" }; var action = new ExecAction() { Path = _recorderLauncherPath, Arguments = ArgumentsManager.JoinArguments(arguments), WorkingDirectory = record.Action.SaveLocationPath, }; definition.Actions.Add(action); } // SetAction
public void ToggleTask(bool enable) { using var ts = new TaskService(); var task = ts.GetTask(TaskName); if (task is null) { var trigger = new LogonTrigger() { UserId = Environment.UserName }; var action = new ExecAction(ExecutablePath, workingDirectory: WorkingDirectory); var description = "GlucoseTray task for " + Environment.UserName; task = ts.AddTask(TaskName, trigger, action, description: description); task.Definition.Settings.ExecutionTimeLimit = TimeSpan.FromSeconds(0); // Don't end task after 72 hour default runtime. task.RegisterChanges(); } task.Enabled = enable; }