private void DisplayTaskScheduleItems() { try { Cursor.Current = Cursors.WaitCursor; btnDelete.Enabled = false; btnEdit.Enabled = false; btnEnableDisable.Enabled = false; btnRun.Enabled = false; using (TaskService ts = new TaskService()) { // Display version and server state Version ver = ts.HighestSupportedVersion; Log.Debug(@"Highest version: {0}", ver); Log.Debug(@"Server: {0} ({1})", ts.TargetServer, ts.Connected ? "Connected" : "Disconnected"); // Output all the tasks in the root folder with their triggers and actions TaskFolder tf = ts.GetFolder(TASK_FOLDER); Log.Debug(@"{0} folder task count ({1}):", TASK_FOLDER, tf?.Tasks.Count ?? 0); taskListView.Tasks = tf?.Tasks ?? null; } } catch { Log.Error(@"Unable to retrieve tasks from the Windows Task Scheduler"); } finally { Cursor.Current = Cursors.Default; } }
public void ReBuildQueue(TaskFolder taskFolder) { List <TaskData> tasks = AddTasksToList(taskFolder); tasks.Sort((x, y) => { if (!x.NextOccurence.HasValue) { if (!y.NextOccurence.HasValue) { return(0); // equal } else { return(-1); // y is greater } } else { if (!y.NextOccurence.HasValue) { return(1); // x is greater } return(((DateTime)x.NextOccurence).CompareTo(y.NextOccurence)); } }); _tasks = tasks; }
} // CreateTask private static TaskFolder GetTaskSchedulerFolder(RecordAdvancedSettings settings, TaskService taskScheduler) { if (string.IsNullOrEmpty(settings.TaskSchedulerFolder)) { settings.TaskSchedulerFolder = ""; return(taskScheduler.RootFolder); } // if TaskFolder folder = null; try { folder = taskScheduler.GetFolder(settings.TaskSchedulerFolder); } catch (DirectoryNotFoundException) { // folder does not exists } catch (FileNotFoundException) { // folder does not exists } // try-catch folder ??= taskScheduler.RootFolder.CreateFolder(settings.TaskSchedulerFolder); return(folder ?? throw new IOException()); } // GetTaskSchedulerFolder
private void MnuFoldersAdd_Click(object sender, EventArgs e) { var parentNode = tvwFolders.SelectedNode; if (parentNode == null) { return; } FormTaskFolder frm = new FormTaskFolder { FolderName = "" }; DialogResult dr = frm.ShowDialog(this); if (dr != DialogResult.OK) { return; } string folderName = frm.FolderName; TaskFolder taskFolder = Controller.Instance.AddChildFolder(_taskFolder.Id); taskFolder.Name = folderName; CreateUIFolders(taskFolder, parentNode); parentNode.ExpandAll(); }
public static Dictionary <int, TaskFolder> ReadTaskFolders() { Database db = Database.GetInstance(); db.OpenIfClosed(); // query string query = "SELECT id,text,status FROM TaskFolder"; SQLiteCommand command = new SQLiteCommand(query, db.GetConnection()); SQLiteDataReader reader = command.ExecuteReader(); // populate folder Dictionary <int, TaskFolder> res = new Dictionary <int, TaskFolder>(); while (reader.Read()) { TaskFolder folder = new TaskFolder(); folder.id = reader.GetInt32(0); folder.text = reader.GetString(1); folder.status = (Status)reader.GetInt32(2); folder.notes = new List <Note>(); folder.tasks = new List <Task>(); res.Add(folder.id, folder); } db.CloseIfOpened(); return(res); }
/// <summary> /// 创建一个计划任务 /// </summary> /// <param name="taskName">计划任务名称</param> /// <param name="taskDescription">计划任务描述</param> /// <param name="trigger">触发条件</param> /// <param name="action">执行任务</param> /// <param name="subFolderName">计划任务所在的文件夹</param> public static void CreateTask(string subFolderName, string taskName, string taskDescription, Trigger trigger, Microsoft.Win32.TaskScheduler.Action action) { using (TaskService ts = new TaskService()) { using (TaskDefinition td = ts.NewTask()) { td.RegistrationInfo.Description = taskDescription; td.RegistrationInfo.Author = System.Security.Principal.WindowsIdentity.GetCurrent().Name; #region LogonType元素和UserId元素被一起使用,以定义需要运行这些任务的用户。 //http://stackoverflow.com/questions/8170236/how-to-set-run-only-if-logged-in-and-run-as-with-taskscheduler-in-c //td.Principal.UserId = System.Security.Principal.WindowsIdentity.GetCurrent().Name; //td.Principal.LogonType = TaskLogonType.InteractiveToken; #endregion td.Principal.RunLevel = TaskRunLevel.Highest; td.Triggers.Add(trigger); td.Actions.Add(action); TaskFolder folder = ts.RootFolder; if (!string.IsNullOrWhiteSpace(subFolderName)) { if (!folder.SubFolders.Exists(subFolderName)) { folder = folder.CreateFolder(subFolderName); } else { folder = folder.SubFolders[subFolderName]; } } folder.RegisterTaskDefinition(taskName, td); folder.Dispose(); folder = null; } } }
/// <summary> /// Deletes all schedulers. /// </summary> public void DeleteAllSchedulers() { try { var taskScheduler = new TaskService(); TaskFolder taskFolder = taskScheduler.GetFolder("\\" + PullDataScheduler.SchedulerGroupName); IEnumerable <TaskFolder> taskFolders = GetTaskFolder(taskScheduler, PullDataScheduler.SchedulerGroupName); if (taskFolders.Any()) { TaskCollection tasks = taskFolder.GetTasks(); if (tasks != null) { foreach (Task task in tasks) { if (task.State == TaskState.Running) { task.Stop(); } taskFolder.DeleteTask(task.Name, false); } } } taskFolder = taskScheduler.GetFolder("\\"); taskFolder.DeleteFolder(PullDataScheduler.SchedulerGroupName, false); } catch (Exception exception) { Logger.LogMessage(exception.Message, "DeleteSchedulers", LogType.Error, exception); //NotificationHelper.ShowMessage(exception.Message, ResourceHelper.GetResourceValue("CaptionError")); } }
//TaskFolder preparation private void addTaskFolder(TaskFolder tf) { PageFolderLook pageFL = new PageFolderLook(tf); //EVENT ADD pageFL.AnyChange += EventButApplyClicked; //delete event //pageFL.ButtonClickedHandler -= ButtonClickedEvent; Frame myFrame = new Frame(); myFrame.Margin = new Thickness(10, 10, 10, 10); myFrame.Navigate(pageFL); if (tasksCnt % 5 == 0) { StackPanel sp = new StackPanel(); sp.Orientation = Orientation.Horizontal; stackPanels.Add(sp); panelTasks.Children.Add(sp); } stackPanels[stackPanels.Count - 1].Children.Add(myFrame); tasksCnt++; }
public void RemoveTask() { using (TaskService taskService = new TaskService()) { TaskFolder taskFolder = taskService.GetFolder(folder); try { taskFolder.DeleteTask(light); } catch { } try { taskFolder.DeleteTask(dark); } catch { } try { taskFolder.DeleteTask(updater); } catch { } try { taskService.RootFolder.DeleteFolder(folder); } catch { } } }
private void checkBox1_CheckedChanged(object sender, EventArgs e) { dataGridView3.Rows.Clear(); string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; string computername = System.Environment.MachineName; TaskService ts = new TaskService(); TaskFolder tf = ts.RootFolder; foreach (Microsoft.Win32.TaskScheduler.Task t in tf.Tasks) { try { foreach (Microsoft.Win32.TaskScheduler.Trigger trg in t.Definition.Triggers) { if (checkBox1.Checked != true) { if (trg.ToString() == "Run at system startup" || trg.ToString() == "At system startup" || trg.ToString() == "At log on of " + computername + "\\" + userName || trg.ToString() == "Run at user logon") { this.dataGridView3.Rows.Add(true, t.Name, trg.ToString()); break; } } else { this.dataGridView3.Rows.Add(true, t.Name, trg.ToString()); break; } } } catch { } } }
public void ManyTasks(string numberOfTasks) { TaskService localTaskService = new TaskService(); try { for (var i = int.Parse(numberOfTasks); i > 0; i--) { TaskDefinition td = localTaskService.NewTask(); td.RegistrationInfo.Description = "Does something"; td.Triggers.Add(new DailyTrigger { DaysInterval = 2 }); td.Actions.Add(new ExecAction("cmd.exe", "/c echo WarewolfAgent.exe", null)); TaskFolder localWarewolfFolder = localTaskService.GetFolder("Warewolf"); if (localWarewolfFolder != null) { localWarewolfFolder.RegisterTaskDefinition(@"UILoadTest" + i.ToString(), td); } else { Assert.Fail("Task scheduler has no Warewolf folder."); } } } finally { ScenarioContext.Current.Add("localTaskService", localTaskService); ScenarioContext.Current.Add("numberOfTasks", numberOfTasks); } }
private void MnuTasksAddNew_Click(object sender, EventArgs e) { FormTaskData frm = new FormTaskData { TaskData = Controller.CreateNewTask() }; DialogResult dr = frm.ShowDialog(this); if (dr != DialogResult.OK) { return; } Controller.Instance.AddChildTask(_taskFolder.Id, frm.TaskData); TaskFolder folder = _taskFolder; _listViewChangedProgramatically = true; lstTasks.Items.Clear(); for (int i = 0; i < folder.Tasks.Count; i++) { var x = lstTasks.Items.Add(folder.Tasks[i].Name); x.Tag = folder.Tasks[i].Id; x.SubItems.Add(GetNextOccurenceText(folder.Tasks[i])); x.SubItems.Add(folder.Tasks[i].ActioningData.Command); x.SubItems.Add(folder.Tasks[i].DebugData.TaskStatus.ToString()); x.SubItems.Add(folder.Tasks[i].IsEnabled.ToString()); x.SubItems.Add(GetLastRunText(folder.Tasks[i])); } AutoSizeColumnList(lstTasks); _listViewChangedProgramatically = false; OnTaskItemSelected(); }
public static List <RunningTasks> StartAudit() { List <RunningTasks> lstTask = new List <RunningTasks>(); try { using (TaskService ts = new TaskService()) { //Gets List Of Tasks in a folder. For Root Folder use backslash TaskFolder taskFolder = ts.GetFolder(@"\"); TaskCollection col = taskFolder.Tasks; foreach (Task task in col) { RunningTasks tss = new RunningTasks(); tss.TaskName = task.Name; tss.NextRunTime = task.NextRunTime; tss.Status = task.State.ToString(); lstTask.Add(tss); } } } catch (Exception) { } return(lstTask); }
public void SaveTaskToOutlookFolder() { OutlookSession os = new OutlookSession(); TaskFolder folder = os.Tasks; folder.Items.Add(temp); }
private List <TaskData> AddTasksToList(TaskFolder folder) { List <TaskData> tasks = new List <TaskData>(); AddTasksToList(folder, tasks); return(tasks); }
private static List <Microsoft.Win32.TaskScheduler.Task> GetReadyAndRunningTasks( TaskFolder folder, List <Microsoft.Win32.TaskScheduler.Task> taskCollection = null) { if (taskCollection == null) { taskCollection = new List <Microsoft.Win32.TaskScheduler.Task>(); } var tasks = folder.Tasks; foreach (Microsoft.Win32.TaskScheduler.Task task in tasks) { if (task.State != TaskState.Disabled) { taskCollection.Add(task); } } foreach (TaskFolder subFolder in folder.SubFolders) { GetReadyAndRunningTasks(subFolder, taskCollection); } return(taskCollection); }
private static void OnRemove(Task task, ref bool returnValue) { TaskService Scheduler = task.TaskService; TaskFolder RootFolder = Scheduler.RootFolder; RootFolder.DeleteTask(task.Name, false); }
// // See the code in the following location for how to do these things // http://taskscheduler.codeplex.com/wikipage?title=Examples&referringTitle=Documentation // private void btnGetSchedules_Click(object sender, EventArgs e) { try { EnableScheduleButtons(false); toolStripStatusLabel1.Text = DateTime.Now.ToString("u"); toolStripProgressBar1.DisplayText = "Starting"; toolStripProgressBar1.State = ProgressBarState.Normal; toolStripProgressBar1.Style = ProgressBarStyle.Marquee; toolStripProgressBar1.Value = 0; UseWaitCursor = true; using (TaskService ts = new TaskService()) { // Display version and server state Version ver = ts.HighestSupportedVersion; Log.Info("Highest version: {0}", ver); Log.Info("Server: {0} ({1})", ts.TargetServer, ts.Connected ? "Connected" : "Disconnected"); // Output all the tasks in the root folder with their triggers and actions TaskFolder tf = ts.RootFolder; Log.Info("Root folder tasks ({0}):", tf.Tasks.Count); lstHistory.Tasks = tf.Tasks; //lstHistory.Tasks = ts.FindAllTasks(); } } finally { toolStripProgressBar1.Style = ProgressBarStyle.Continuous; UseWaitCursor = false; toolStripProgressBar1.DisplayText = string.Empty; toolStripProgressBar1.Value = 0; EnableScheduleButtons(true); } }
public bool RunTask(string taskname) { bool result = false; try { using (TaskService ts = new TaskService()) { TaskFolder tf = ts.GetFolder("BatchUpgrader"); foreach (Task task in tf.Tasks) { if (task.Name == taskname) { if (task.Enabled) { task.Run(); } else { task.Enabled = true; task.Run(); task.Enabled = false; } return(true); } } } } catch (Exception ex) { MessageBox.Show("Task Name:" + taskname + "\nCannot run the task." + ex.Message, "Run Tasks", MessageBoxButton.OK); } return(result); }
public void RemoveAllTasks() { using (TaskService taskService = new TaskService()) { TaskFolder taskFolder = taskService.GetFolder(folder); if (taskFolder != null) { foreach (var v in taskFolder.GetTasks()) { try { taskFolder.DeleteTask(v.ToString(), false); Console.WriteLine("Deleted Task: " + v.ToString()); } catch { } } try { taskService.RootFolder.DeleteFolder(folder, false); } catch { } } } }
/// <summary> /// Crea una tarea mas especifica /// </summary> /// <param name="name"></param> /// <param name="description"></param> /// <param name="pathExe"></param> /// <param name="startHour"></param> /// <param name="daysInterval"></param> /// <param name="allowRun"></param> /// <param name="argum"></param> /// <returns></returns> public static string CreateTask(string name, string description, string pathExe, double startHour, short daysInterval, bool allowRun = false, string argum = "") { string response = ""; // Get the service on the local machine using (TaskService ts = new TaskService()) { string taskName = name; TaskDefinition td = ts.NewTask(); td.RegistrationInfo.Description = description; DailyTrigger dTrigger = td.Triggers.Add(new DailyTrigger()); if (startHour != 0) { dTrigger.StartBoundary = DateTime.Today + TimeSpan.FromHours(startHour); } if (daysInterval != 0) { dTrigger.DaysInterval = daysInterval; } if (allowRun) { dTrigger.Repetition.Interval = TimeSpan.FromSeconds(60); } td.Settings.MultipleInstances = TaskInstancesPolicy.StopExisting; td.Actions.Add(new ExecAction(pathExe, argum)); ts.RootFolder.RegisterTaskDefinition(taskName, td, TaskCreation.CreateOrUpdate, null, null, TaskLogonType.InteractiveToken, null); //SHOW ALL INFORAMTION OF NEW TASKs TaskFolder tf = ts.RootFolder; Microsoft.Win32.TaskScheduler.Task runningTask = tf.Tasks[taskName]; response = "==============================" + Environment.NewLine; response += "New task:" + taskName + Environment.NewLine; response += "Triggers:"; for (int i = 0; i < runningTask.Definition.Triggers.Count; i++) { response += string.Format("{0}", runningTask.Definition.Triggers[i]) + Environment.NewLine; } response += "Actions:" + Environment.NewLine; for (int i = 0; i < runningTask.Definition.Actions.Count; i++) { response += string.Format("{0}", runningTask.Definition.Actions[i]) + Environment.NewLine; response += Environment.NewLine; } return(response); } }
private void AddFolderToList(TaskFolder folder) { _foldersById.TryAdd(folder.Id, folder); for (int i = 0; i < folder.SubFolders.Count; i++) { AddFolderToList(folder.SubFolders[i]); } }
public static TaskCollection GetAllTasksFromFolder() { OutlookSession os = new OutlookSession(); TaskFolder folder = os.Tasks; TaskCollection collection = folder.Items; return(collection); }
public void DeleteFolder(string folderId, string parentFolderId) { TaskFolder folder = GetFolderById(folderId); TaskFolder parentFolder = GetFolderById(parentFolderId); _foldersById.TryRemove(folder.Id, out _); parentFolder.SubFolders.Remove(folder); }
public void DeleteTask(string taskId, string folderId) { TaskFolder folder = GetFolderById(folderId); TaskData task = GetTaskBeId(taskId); folder.Tasks.Remove(task); _tasksById.TryRemove(taskId, out _); }
public IEnumerable <PersonalTask> FindBy(Account account, TaskFolder folder) { return(this.FindAll(Expression.Eq("CreatorAccountId", account.ID) , folder == null ? Expression.IsNull("TaskFolderId") : Expression.Eq("TaskFolderId", folder.ID), IsNotTrashedCriteria)); }
public void Init() { _service = new TaskService(); _folder = _service.RootFolder.SubFolders.Any(a => a.Name == "WarewolfTestFolder") ? _service.GetFolder("WarewolfTestFolder") : _service.RootFolder.CreateFolder("WarewolfTestFolder"); var task = _service.NewTask(); task.Actions.Add(new ExecAction("Notepad.exe")); _folder.RegisterTaskDefinition("TestTask", task, TaskCreation.Create, "LocalSchedulerAdmin", "987Sched#@!", TaskLogonType.None); }
public void Dispose() { if (_service != null) { _service.Dispose(); _service = null; _folder = null; } }
public void Init() { _service = new TaskService(); _folder = _service.RootFolder.SubFolders.Any(a => a.Name == "WarewolfTestFolder") ? _service.GetFolder("WarewolfTestFolder") : _service.RootFolder.CreateFolder("WarewolfTestFolder"); var task = _service.NewTask(); task.Actions.Add(new ExecAction("Notepad.exe")); _folder.RegisterTaskDefinition("TestTask", task); }
public static void Delete(string name) { TaskFolder folder = loadTaskFolder(); try { folder.DeleteTask(name); } catch (FileNotFoundException) { } }
/// <summary>设置任务所在的任务目录 /// </summary> /// <param name="folder"></param> public void SetTaskFolder(TaskFolder folder) { Assert.IsValid(folder); if (this.TaskFolderId == folder.ID) { return; } if (folder is PersonalTaskFolder) { Assert.AreEqual(this.CreatorAccountId, (folder as PersonalTaskFolder).OwnerAccountId); } this.TaskFolderId = folder.ID; this.MakeChange(); }
void ITaskFolderService.Create(TaskFolder folder) { _repository.Add(folder); if (this._log.IsInfoEnabled) this._log.InfoFormat("新增任务表{0}#{1}|{2}", folder, folder.ID, folder.Name); }
void ITaskFolderService.Delete(TaskFolder folder) { _repository.Remove(folder); //HACK:目前不会删除任务表下的所有任务 if (this._log.IsInfoEnabled) this._log.InfoFormat("删除任务表#{0}", folder.ID); }
IEnumerable<PersonalTask> IPersonalTaskService.GetTasks(Account account, TaskFolder folder) { return _repository.FindBy(account, folder); }
private bool FindTaskInFolder(TaskFolder fld, Regex taskName, ref List<Task> results, bool recurse = true) { results.AddRange(fld.GetTasks(taskName)); if (recurse) foreach (TaskFolder folder in fld.SubFolders) if (FindTaskInFolder(folder, taskName, ref results, recurse)) return true; return false; }
void ITaskFolderService.Update(TaskFolder folder) { _repository.Update(folder); }
private Sort[] GetSorts(TaskFolder a, string by) { return !string.IsNullOrWhiteSpace(a.Settings[by]) ? _serializer.JsonDeserialize<Sort[]>(a.Settings[by]) : _emptySorts; }
private Sort[] ParseSortsByDueTime(Account account, TaskFolder folder, params TaskInfo[] tasks) { return this.ParseSortsByDueTime(this.GetSorts(folder, SORT_DUETIME), tasks); }
private Sort[] ParseSortsByPriority(Account account, TaskFolder folder, params TaskInfo[] tasks) { return this.ParseSortsByPriority(this.GetSorts(folder, SORT_PRIORITY), tasks); }