void SaveTask() { bool isNewTask = true; try { var service = new TaskService(); TaskDefinition td = service.NewTask(); Microsoft.Win32.TaskScheduler.TriggerCollection trgCollection; var oldTriggerDate = new DateTime(); Task task = service.FindTask(MainWindowViewModel.FreemiumDriverScanTaskName); if (task != null) { isNewTask = false; oldTriggerDate = task.Definition.Triggers.Count > 0 ? task.Definition.Triggers[0].StartBoundary.Date : DateTime.Today; task.Definition.Triggers.Clear(); trgCollection = task.Definition.Triggers; } else { td.RegistrationInfo.Description = WPFLocalizeExtensionHelpers.GetUIString("WindowsTaskRegistrationInfo"); td.Settings.Enabled = true; td.Actions.Add(new ExecAction(Environment.CurrentDirectory + @"\1Click.exe")); trgCollection = td.Triggers; } TimeSpan selectedTime = TimeSpan.Parse(((ComboBoxItem)AutoScanTime.SelectedValue).Content.ToString()); switch (AutoScanPeriod.SelectedIndex) { case (int)Schedule.Daily: { var dTrigger = new DailyTrigger {DaysInterval = 1}; if (isNewTask) dTrigger.StartBoundary = DateTime.Today.Date + selectedTime; else dTrigger.StartBoundary = oldTriggerDate + selectedTime; trgCollection.Add(dTrigger); break; } case (int)Schedule.Weekly: { var wTrigger = new WeeklyTrigger(); switch (AutoScanDay.SelectedIndex) { case (int)DayOfWeek.Monday: { wTrigger.DaysOfWeek = DaysOfTheWeek.Monday; break; } case (int)DayOfWeek.Tuesday: { wTrigger.DaysOfWeek = DaysOfTheWeek.Tuesday; break; } case (int)DayOfWeek.Wednesday: { wTrigger.DaysOfWeek = DaysOfTheWeek.Wednesday; break; } case (int)DayOfWeek.Thursday: { wTrigger.DaysOfWeek = DaysOfTheWeek.Thursday; break; } case (int)DayOfWeek.Friday: { wTrigger.DaysOfWeek = DaysOfTheWeek.Friday; break; } case (int)DayOfWeek.Saturday: { wTrigger.DaysOfWeek = DaysOfTheWeek.Saturday; break; } case (int)DayOfWeek.Sunday: { wTrigger.DaysOfWeek = DaysOfTheWeek.Sunday; break; } } trgCollection.Add(wTrigger); foreach (WeeklyTrigger trg in trgCollection) { if (isNewTask) trg.StartBoundary = DateTime.Today.Date + selectedTime; else trg.StartBoundary = oldTriggerDate + selectedTime; trg.WeeksInterval = 1; } break; } case (int)Schedule.Monthly: { var mTrigger = new MonthlyTrigger(); if (isNewTask) mTrigger.StartBoundary = DateTime.Today.Date + selectedTime; else mTrigger.StartBoundary = oldTriggerDate + selectedTime; mTrigger.MonthsOfYear = MonthsOfTheYear.AllMonths; mTrigger.DaysOfMonth = new int[] { Int16.Parse(((ComboBoxItem)AutoScanDate.SelectedValue).Content.ToString()) }; trgCollection.Add(mTrigger); break; } } // Register the task in the root folder if (isNewTask) service.RootFolder.RegisterTaskDefinition(MainWindowViewModel.FreemiumDriverScanTaskName, td); else task.RegisterChanges(); TaskManager.UpdateTaskStatus(MainWindowViewModel.FreemiumDriverScanTaskName, AutoScan.IsChecked == true); } catch { } }
public static void AddStores2TaskScheduler(string strStoresPath, string strActionPath) { string[] strXMLFiles = Directory.GetFiles(strStoresPath, "*.xml"); TaskService ts = new TaskService(); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(""); Console.WriteLine("Adding stores to the Task Scheduler"); Console.ForegroundColor = ConsoleColor.Green; foreach (string strXMLFile in strXMLFiles) { string storeName = Path.GetFileName(strXMLFile); string taskName = @"BC Store " + storeName; Task t = ts.FindTask(taskName); if (t == null) { Console.WriteLine(" + " + storeName); DailyTrigger dt = new DailyTrigger(); dt.StartBoundary = DateTime.Today.Date; dt.Repetition.Duration = TimeSpan.FromMinutes(1430); dt.Repetition.Interval = TimeSpan.FromMinutes(2); ts.AddTask(taskName, dt, new ExecAction(strActionPath, strXMLFile, null)); Thread.Sleep(500); } } Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("All stores added"); Console.WriteLine(""); Console.WriteLine(""); Console.ForegroundColor = ConsoleColor.White; }
internal static void FindTask(TaskService ts, System.IO.TextWriter output, params string[] arg) { try { Task t = ts.FindTask(arg[0]); if (t == null) output.WriteLine(string.Format("Task '{0}' not found.", arg[0])); else { output.WriteLine(string.Format("Task '{0}' found. Created on {1:g} and last run on {2:g}.", t.Name, t.Definition.RegistrationInfo.Date, t.LastRunTime)); if (t.Definition.Triggers.ContainsType(typeof(CustomTrigger))) { foreach (var tr in t.Definition.Triggers) { CustomTrigger ct = tr as CustomTrigger; if (ct != null && ct.Properties.Count > 0) { output.WriteLine("Custom Trigger Properties:"); int i = 0; foreach (var name in ct.Properties.Names) output.WriteLine("{0}. {1} = {2}", ++i, name, ct.Properties[name]); } } } } } catch (Exception ex) { output.WriteLine(ex.ToString()); } }
public bool CreateOrActivate(String TaskName, String FullExecuteableFileName, TimeSpan RetryIntervall) { //if (!IsAdministrator()) // return false; using (TaskService taskService = new TaskService()) { Task task = taskService.FindTask(TaskName); if (task == null) { TaskDefinition taskDefinition = CreateTask(taskService, TaskName, RetryIntervall); taskDefinition.Actions.Add(new ExecAction(FullExecuteableFileName)); taskDefinition.RegistrationInfo.Description = $"WPMedia created Task for " + $"{Path.GetFileNameWithoutExtension(FullExecuteableFileName)}"; taskDefinition.Settings.MultipleInstances = TaskInstancesPolicy.IgnoreNew; taskDefinition.Settings.AllowDemandStart = true; taskDefinition.Settings.AllowHardTerminate = false; taskDefinition.Settings.DisallowStartIfOnBatteries = false; taskDefinition.RegistrationInfo.Author = "WPMediaAutoRegistration"; if (taskDefinition.Validate()) task = taskService.RootFolder.RegisterTaskDefinition(TaskName, taskDefinition); else throw new Exception($"{TaskName} Scheduling for {FullExecuteableFileName} failed"); } task.Enabled = true; } return true; }
public static bool StartupTaskExists() { using (TaskService _taskService = new TaskService()) { return _taskService.FindTask(_taskName) != null; } }
public void clearSchedules() { string strTaskID = ""; try { // Get the service on the local machine TaskService ts = new TaskService(); // Delete Schedules DataTable dt = this.GetSchedules(1); foreach (DataRow dr in dt.Rows) { strTaskID = dr["TaskID"].ToString(); if (ts.FindTask(strTaskID, true) != null) { // Remove the task we just created ts.RootFolder.DeleteTask(strTaskID); } // Delete schedules follow taskid this.DeleleSchedules(strTaskID); } } catch (Exception ex) { throw ex; } }
private void setupTask(string tskName) { using (Scheduler.TaskService tsrv = new Scheduler.TaskService()) { Scheduler.TaskDefinition tskDef = tsrv.FindTask(tskName).Definition; tskDef.Settings.DisallowStartIfOnBatteries = false; tskDef.Settings.RunOnlyIfNetworkAvailable = true; tskDef.RegistrationInfo.Author = _taskAuthor; tskDef.RegistrationInfo.Documentation = "TimeSharp time keeper utility"; tskDef.Principal.RunLevel = Scheduler.TaskRunLevel.Highest; tskDef.Settings.MultipleInstances = Scheduler.TaskInstancesPolicy.IgnoreNew; tskDef.Settings.WakeToRun = false; tskDef.Settings.Compatibility = Scheduler.TaskCompatibility.V2_1; //add auxiliary triggers Scheduler.SessionStateChangeTrigger unlockSessionTrigger = new Scheduler.SessionStateChangeTrigger(Scheduler.TaskSessionStateChangeType.SessionUnlock) { Enabled = true }; Scheduler.LogonTrigger logonTrigger = new Scheduler.LogonTrigger() { Enabled = true, Delay = TimeSpan.FromMinutes(1), StartBoundary = DateTime.Now, ExecutionTimeLimit = TimeSpan.FromMinutes(5) }; tskDef.Triggers.AddRange(new Scheduler.Trigger[] { unlockSessionTrigger, logonTrigger }); tsrv.RootFolder.RegisterTaskDefinition(tskName, tskDef, Scheduler.TaskCreation.CreateOrUpdate, _adminsGroupName, null, Scheduler.TaskLogonType.Group); } }
private void btnInput_Click(object sender, EventArgs e) { string strTaskID = ""; string appPath = System.Configuration.ConfigurationManager.AppSettings["AutoGetOdds"]; Application.DoEvents(); Cursor.Current = Cursors.WaitCursor; try { // Get the service on the local machine TaskService ts = new TaskService(); // Delete Schedules DataTable dt = oddBO.GetSchedules(1); foreach (DataRow dr in dt.Rows) { strTaskID = dr["TaskID"].ToString(); if (ts.FindTask(strTaskID, true) != null) { // Remove the task we just created ts.RootFolder.DeleteTask(strTaskID); } // Delete schedules follow taskid oddBO.DeleleSchedules(strTaskID); } DateTime currDate = dtpDate.Value; // Create Schedules dt = oddBO.GetSchedules(0, currDate); foreach (DataRow dr in dt.Rows) { strTaskID = dr["TaskID"].ToString(); // Create a new task definition and assign properties TaskDefinition td = ts.NewTask(); Trigger t = new TimeTrigger(); t.StartBoundary = Convert.ToDateTime(dr["RunTime"].ToString()); td.RegistrationInfo.Description = "Get odd at " + dr["RunTime"].ToString(); // Create a trigger that will fire the task at this time every other day td.Triggers.Add(t); // Create an action that will launch Notepad whenever the trigger fires td.Actions.Add(new ExecAction(appPath, "\"" + strTaskID + "\"", null)); // Register the task in the root folder ts.RootFolder.RegisterTaskDefinition(strTaskID, td); } MessageBox.Show("Schedules have inputed successfully!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { Cursor.Current = Cursors.WaitCursor; } }
public static bool PersistTask(bool startAtLogon, bool startForAllUsers) { WinTasks.TaskService ts = new WinTasks.TaskService(); try { WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); bool isElevated = (new WindowsPrincipal(currentIdentity).IsInRole(WindowsBuiltInRole.Administrator)); WinTasks.Task task = ts.FindTask(Application.ProductName, false); if (startAtLogon) { if (startForAllUsers && !isElevated) { return PersistTaskElevated(startAtLogon, startForAllUsers); } else { WinTasks.LogonTrigger trigger = (WinTasks.LogonTrigger)WinTasks.LogonTrigger.CreateTrigger(WinTasks.TaskTriggerType.Logon); trigger.Enabled = true; trigger.StartBoundary = DateTime.Today; if (startForAllUsers) trigger.UserId = null; else trigger.UserId = currentIdentity.Name; WinTasks.ExecAction action = (WinTasks.ExecAction)WinTasks.ExecAction.CreateAction(WinTasks.TaskActionType.Execute); action.Path = Application.ExecutablePath; action.WorkingDirectory = System.IO.Path.GetDirectoryName(Application.ExecutablePath); if (task == null) { task = ts.AddTask(Application.ProductName, trigger, action, currentIdentity.Name); } else { task.Definition.Triggers.Clear(); task.Definition.Triggers.Add(trigger); task.Definition.Actions.Clear(); task.Definition.Actions.Add(action); task.RegisterChanges(); } } } else if (task != null) { ts.GetFolder("\\").DeleteTask(task.Name); } } catch { return false; } finally { ts.Dispose(); } return true; }
public static void DeleteTask(string taskName) { Task task = null; try { TaskService service = new TaskService(); task = service.FindTask(taskName, true); if (task != null) service.RootFolder.DeleteTask(taskName); } catch { } }
/// <summary> /// Gets task by its name /// </summary> /// <param name="taskName">task name</param> /// <returns></returns> public static Task GetTaskByName(string taskName) { Task task = null; try { TaskService service = new TaskService(); task = service.FindTask(taskName, true); } catch { } return task; }
public void UnScheduleBackup() { // Get the service on the local machine using (var ts = new TaskService()) { Task existingTask = ts.FindTask("EC2 Backup"); if (null != existingTask) { // Remove the task we just created ts.RootFolder.DeleteTask(existingTask.Name); } } }
public static void UpdateTaskStatus(string taskName, bool isEnabled) { try { TaskService service = new TaskService(); Task task = service.FindTask(taskName, true); if (task != null) { task.Enabled = isEnabled; task.RegisterChanges(); } } catch{} }
public bool Disable(String TaskName) { if (!IsAdministrator()) return false; using (TaskService taskService = new TaskService()) { Task task = taskService.FindTask(TaskName); if (task == null) { return false; } task.Enabled = false; return true; } }
public SkylineNightly() { InitializeComponent(); startTime.Value = DateTime.Parse(Settings.Default.StartTime); textBoxFolder.Text = Settings.Default.NightlyFolder; includePerfTests.Checked = Settings.Default.PerfTests; if (string.IsNullOrEmpty(textBoxFolder.Text)) textBoxFolder.Text = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "SkylineNightly"); // Not L10N using (var ts = new TaskService()) { var task = ts.FindTask(Nightly.NIGHTLY_TASK_NAME); enabled.Checked = (task != null); } }
public static void Start(string command) { using (var ts = new TaskService()) { var td = ts.NewTask(); td.RegistrationInfo.Description = "start " + taskName + " limited user"; td.Actions.Add(new ExecAction(command)); td.Settings.Priority = ProcessPriorityClass.Normal; td.Principal.RunLevel = TaskRunLevel.LUA; td.Settings.AllowDemandStart = true; td.Settings.DisallowStartIfOnBatteries = false; td.Settings.StopIfGoingOnBatteries = false; var ret = ts.RootFolder.RegisterTaskDefinition(taskName, td); var fooTask = ts.FindTask(taskName, true); fooTask.Run(); ts.RootFolder.DeleteTask(taskName); } }
private void deleteBtn_Click(object sender, EventArgs e) { var result = MessageBox.Show("This will cancel automatic wallpaper changing.\nDo you wish to continue?", "Continue?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); // User wants to delete the wallpaper setter task if (result == DialogResult.Yes) { using (TaskService taskService = new TaskService()) { if (taskService.FindTask("Wallpaper Setter") != null) { try { taskService.RootFolder.DeleteTask("Wallpaper Setter"); MessageBox.Show("Save successful!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } } } } }
void LoadTaskParams() { try { var service = new TaskService(); TaskDefinition td = service.NewTask(); Microsoft.Win32.TaskScheduler.TriggerCollection trgCollection; var oldTriggerDate = new DateTime(); Task task = service.FindTask(MainWindowViewModel.FreemiumDriverScanTaskName); if (task != null) { AutoScan.IsChecked = task.Enabled; if (task.Definition.Triggers.Count > 0) { oldTriggerDate = task.Definition.Triggers[0].StartBoundary.Date; } trgCollection = task.Definition.Triggers; foreach (Microsoft.Win32.TaskScheduler.Trigger trg in task.Definition.Triggers) { string time = trg.StartBoundary.ToString("hh:mm"); byte index = 0; byte i = 0; foreach (var item in AutoScanTime.Items) { if (((ComboBoxItem)item).Content.ToString() == time) { index = i; break; } i++; } AutoScanTime.SelectedIndex = index; if (trg.TriggerType == TaskTriggerType.Daily) { AutoScanPeriod.SelectedIndex = (int)Schedule.Daily; } else if (trg.TriggerType == TaskTriggerType.Weekly) { AutoScanPeriod.SelectedIndex = (int)Schedule.Weekly; var wTrigger = (trg as WeeklyTrigger); if (wTrigger.DaysOfWeek == DaysOfTheWeek.Monday) { AutoScanDay.SelectedIndex = (int)DayOfWeek.Monday; } if (wTrigger.DaysOfWeek == DaysOfTheWeek.Tuesday) { AutoScanDay.SelectedIndex = (int)DayOfWeek.Tuesday; } if (wTrigger.DaysOfWeek == DaysOfTheWeek.Wednesday) { AutoScanDay.SelectedIndex = (int)DayOfWeek.Wednesday; } if (wTrigger.DaysOfWeek == DaysOfTheWeek.Thursday) { AutoScanDay.SelectedIndex = (int)DayOfWeek.Thursday; } if (wTrigger.DaysOfWeek == DaysOfTheWeek.Friday) { AutoScanDay.SelectedIndex = (int)DayOfWeek.Friday; } if (wTrigger.DaysOfWeek == DaysOfTheWeek.Saturday) { AutoScanDay.SelectedIndex = (int)DayOfWeek.Saturday; } if (wTrigger.DaysOfWeek == DaysOfTheWeek.Sunday) { AutoScanDay.SelectedIndex = (int)DayOfWeek.Sunday; } } else if (trg.TriggerType == TaskTriggerType.Monthly || trg.TriggerType == TaskTriggerType.MonthlyDOW) { AutoScanPeriod.SelectedIndex = (int)Schedule.Monthly; if (trg.TriggerType == TaskTriggerType.Monthly) { string date = (trg as MonthlyTrigger).DaysOfMonth[0].ToString(CultureInfo.InvariantCulture); int selectedIndex = 0; int k = 0; foreach (var item in AutoScanDate.Items) { if (((ComboBoxItem)item).Content.ToString() == date) { selectedIndex = k; break; } k++; } AutoScanDate.SelectedIndex = selectedIndex; } } } } else { AutoScan.IsChecked = false; AutoScanPeriod.SelectedIndex = 2; AutoScanDate.Visibility = Visibility.Visible; AutoScanDate.SelectedIndex = 0; AutoScanDay.SelectedIndex = (int)DayOfWeek.NADay; AutoScanTime.SelectedIndex = 11; } } catch { } }
private void ButtonClearTaskClick(object sender, EventArgs e) { using (var task = new TaskService()) { var foundTask = task.FindTask("AllegroParser"); if (foundTask != null) { task.RootFolder.DeleteTask(foundTask.Name); } } MessageBox.Show("Usunięto zadanie!"); }
/// <summary> /// Updates action type of task - "scan only" or "scan and fix" /// </summary> /// <param name="taskName">task name</param> /// <param name="scanOnly">true - if we need to scan only, false if we need to scan and fix</param> public static void UpdateTaskActionType(string taskName, bool scanOnly) { try { TaskService service = new TaskService(); Task task = service.FindTask(taskName, true); if (task != null) { if (scanOnly) { task.Definition.Actions[0] = new ExecAction(Environment.CurrentDirectory + "\\1Click.exe", System.Diagnostics.Process.GetCurrentProcess().ProcessName, Environment.CurrentDirectory); } else { task.Definition.Actions[0] = new ExecAction(Environment.CurrentDirectory + "\\1Click.exe" , System.Diagnostics.Process.GetCurrentProcess().ProcessName+" "+ScanAndFixCommandLineArg, Environment.CurrentDirectory); } task.RegisterChanges(); } } catch { } }
/// <summary> /// Saves all the settings setted in the UI /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void btnOK_Click(object sender, EventArgs e) { bool isNewTask = true; try { TaskService service = new TaskService(); TaskDefinition td = service.NewTask(); TriggerCollection trgCollection; DateTime oldTriggerDate = new DateTime(); Task task = service.FindTask("PCCleaner1ClickMaint"); if (task != null) { isNewTask = false; oldTriggerDate = task.Definition.Triggers.Count > 0 ? task.Definition.Triggers[0].StartBoundary.Date : DateTime.Today; task.Definition.Triggers.Clear(); trgCollection = task.Definition.Triggers; } else { td.RegistrationInfo.Description = "PCCleaner 1 ClickMaint"; td.Settings.Enabled = true; td.Actions.Add(new ExecAction(Environment.CurrentDirectory + "\\1Click.exe", System.Diagnostics.Process.GetCurrentProcess().ProcessName, Environment.CurrentDirectory)); trgCollection = td.Triggers; } if (cmbSelectSchedule.SelectedIndex == (int)Schedule.Daily) { DailyTrigger dTrigger = new DailyTrigger { DaysInterval = (short)nudDays.Value }; if (isNewTask) dTrigger.StartBoundary = DateTime.Today.Date + timePicker.Value.TimeOfDay; else dTrigger.StartBoundary = oldTriggerDate + timePicker.Value.TimeOfDay; trgCollection.Add(dTrigger); } else if (cmbSelectSchedule.SelectedIndex == (int)Schedule.Weekly) { WeeklyTrigger wTrigger = new WeeklyTrigger(); if (!chkMon.Checked && !chkTue.Checked && !chkWed.Checked && !chkThu.Checked && !chkFri.Checked && !chkSat.Checked && !chkSun.Checked) { MessageBox.Show(WPFLocalizeExtensionHelpers.GetUIString("select_day"), System.Windows.Forms.Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (chkMon.Checked && chkTue.Checked && chkWed.Checked && chkThu.Checked && chkFri.Checked && chkSat.Checked && chkSun.Checked) { wTrigger.DaysOfWeek = DaysOfTheWeek.AllDays; trgCollection.Add(wTrigger); cmbSelectSchedule.SelectedIndex = (int)Schedule.Daily; } else { if (chkMon.Checked) { wTrigger = new WeeklyTrigger { DaysOfWeek = DaysOfTheWeek.Monday }; trgCollection.Add(wTrigger); } if (chkTue.Checked) { wTrigger = new WeeklyTrigger { DaysOfWeek = DaysOfTheWeek.Tuesday }; trgCollection.Add(wTrigger); } if (chkWed.Checked) { wTrigger = new WeeklyTrigger { DaysOfWeek = DaysOfTheWeek.Wednesday }; trgCollection.Add(wTrigger); } if (chkThu.Checked) { wTrigger = new WeeklyTrigger { DaysOfWeek = DaysOfTheWeek.Thursday }; trgCollection.Add(wTrigger); } if (chkFri.Checked) { wTrigger = new WeeklyTrigger { DaysOfWeek = DaysOfTheWeek.Friday }; trgCollection.Add(wTrigger); } if (chkSat.Checked) { wTrigger = new WeeklyTrigger { DaysOfWeek = DaysOfTheWeek.Saturday }; trgCollection.Add(wTrigger); } if (chkSun.Checked) { wTrigger = new WeeklyTrigger { DaysOfWeek = DaysOfTheWeek.Sunday }; trgCollection.Add(wTrigger); } } foreach (WeeklyTrigger trg in trgCollection) { if (isNewTask) trg.StartBoundary = DateTime.Today.Date + timePicker.Value.TimeOfDay; else trg.StartBoundary = oldTriggerDate + timePicker.Value.TimeOfDay; trg.WeeksInterval = (short)nudWeeks.Value; } } else if (cmbSelectSchedule.SelectedIndex == (int)Schedule.Monthly) { if (radDay.Checked) { MonthlyTrigger mTrigger = new MonthlyTrigger(); if (isNewTask) mTrigger.StartBoundary = DateTime.Today.Date + timePicker.Value.TimeOfDay; else mTrigger.StartBoundary = oldTriggerDate + timePicker.Value.TimeOfDay; mTrigger.MonthsOfYear = MonthsOfTheYear.AllMonths; mTrigger.DaysOfMonth = new[] { (int)nudDayMonth.Value }; trgCollection.Add(mTrigger); } else if (radMonth.Checked) { MonthlyDOWTrigger mdTrigger = new MonthlyDOWTrigger(); if (cmbday.Text == WPFLocalizeExtensionHelpers.GetUIString("MondayFull")) { mdTrigger.DaysOfWeek = DaysOfTheWeek.Monday; } else if (cmbday.Text == WPFLocalizeExtensionHelpers.GetUIString("TuesdayFull")) { mdTrigger.DaysOfWeek = DaysOfTheWeek.Tuesday; } else if (cmbday.Text == WPFLocalizeExtensionHelpers.GetUIString("WednesdayFull")) { mdTrigger.DaysOfWeek = DaysOfTheWeek.Wednesday; } else if (cmbday.Text == WPFLocalizeExtensionHelpers.GetUIString("ThursdayFull")) { mdTrigger.DaysOfWeek = DaysOfTheWeek.Thursday; } else if (cmbday.Text == WPFLocalizeExtensionHelpers.GetUIString("FridayFull")) { mdTrigger.DaysOfWeek = DaysOfTheWeek.Friday; } else if (cmbday.Text == WPFLocalizeExtensionHelpers.GetUIString("SaturdayFull")) { mdTrigger.DaysOfWeek = DaysOfTheWeek.Saturday; } else if (cmbday.Text == WPFLocalizeExtensionHelpers.GetUIString("SundayFull")) { mdTrigger.DaysOfWeek = DaysOfTheWeek.Sunday; } if (cmbweek.SelectedIndex == 0) { mdTrigger.WeeksOfMonth = WhichWeek.FirstWeek; } else if (cmbweek.SelectedIndex == 1) { mdTrigger.WeeksOfMonth = WhichWeek.SecondWeek; } else if (cmbweek.SelectedIndex == 2) { mdTrigger.WeeksOfMonth = WhichWeek.ThirdWeek; } else if (cmbweek.SelectedIndex == 3) { mdTrigger.WeeksOfMonth = WhichWeek.FourthWeek; } else if (cmbweek.SelectedIndex == 4) { mdTrigger.WeeksOfMonth = WhichWeek.LastWeek; } mdTrigger.MonthsOfYear = MonthsOfTheYear.AllMonths; mdTrigger.StartBoundary = DateTime.Today.Date + timePicker.Value.TimeOfDay; trgCollection.Add(mdTrigger); } } else if (cmbSelectSchedule.SelectedIndex == (int)Schedule.Once) { TimeTrigger tTrigger = new TimeTrigger { StartBoundary = timePickerOnce.Value.Date + timePicker.Value.TimeOfDay }; trgCollection.Add(tTrigger); } else if (cmbSelectSchedule.SelectedIndex == (int)Schedule.AtSystemStartUp) { BootTrigger bTrigger = new BootTrigger { Delay = TimeSpan.FromMinutes(2) }; trgCollection.Add(bTrigger); } else if (cmbSelectSchedule.SelectedIndex == (int)Schedule.AtLogon) { LogonTrigger lTrigger = new LogonTrigger { Delay = TimeSpan.FromSeconds(1) }; trgCollection.Add(lTrigger); } else if (cmbSelectSchedule.SelectedIndex == (int)Schedule.WhenIdel) { IdleTrigger iTrigger = new IdleTrigger(); if (isNewTask) iTrigger.StartBoundary = DateTime.Today.Date + TimeSpan.FromMinutes((double)nudMinutes.Value); else iTrigger.StartBoundary = oldTriggerDate + TimeSpan.FromMinutes((double)nudMinutes.Value); trgCollection.Add(iTrigger); } // Register the task in the root folder if (isNewTask) service.RootFolder.RegisterTaskDefinition(@"PCCleaner1ClickMaint", td); else task.RegisterChanges(); ((OneClickAppsViewModel)Application.Current.MainWindow.DataContext).SchedulerText = lblSchedule.Text; Close(); } catch { } }
public void makeSchedules(DateTime currDate) { string strTaskID = ""; string appPath = System.Configuration.ConfigurationManager.AppSettings["AutoGetOddsMovements"]; try { // Get the service on the local machine TaskService ts = new TaskService(); // Delete Schedules DataTable dt = this.GetSchedules(1); foreach (DataRow dr in dt.Rows) { strTaskID = dr["TaskID"].ToString(); if (ts.FindTask(strTaskID, true) != null) { // Remove the task we just created ts.RootFolder.DeleteTask(strTaskID); } // Delete schedules follow taskid this.DeleleSchedules(strTaskID); } // Create Schedules dt = this.GetSchedules(0, currDate); foreach (DataRow dr in dt.Rows) { strTaskID = dr["TaskID"].ToString(); // Create a new task definition and assign properties TaskDefinition td = ts.NewTask(); Trigger t = new TimeTrigger(); t.StartBoundary = Convert.ToDateTime(dr["RunTime"].ToString()); td.RegistrationInfo.Description = "Get odd at " + dr["RunTime"].ToString(); // Create a trigger that will fire the task at this time every other day td.Triggers.Add(t); // Create an action that will launch Notepad whenever the trigger fires td.Actions.Add(new ExecAction(appPath, "\"" + strTaskID + "\"", null)); //// Run app even user not log on //td.Settings.RunOnlyIfLoggedOn = false; // Register the task in the root folder ts.RootFolder.RegisterTaskDefinition(strTaskID, td); } } catch (Exception ex) { throw ex; } }
private void ButtonOkClick(object sender, EventArgs e) { Settings.Default.Email = textBoxEmail.Text; Settings.Default.Save(); using (var task = new TaskService()) { var foundTask = task.FindTask("AllegroParser"); if (foundTask != null) { task.RootFolder.DeleteTask(foundTask.Name); } var taskDef = task.NewTask(); taskDef.RegistrationInfo.Author = "dev4s"; taskDef.RegistrationInfo.Description = "This is a task for parsing allegro data."; taskDef.RegistrationInfo.Date = DateTime.Now; taskDef.Principal.LogonType = TaskLogonType.InteractiveToken; var file = new FileInfo("APConsole.exe"); var args = string.Format("-u {0} -p {1} -api {2} -sF {3} -rF {4} -em {5}", Password.Decrypt(Settings.Default.Login), Password.Decrypt(Settings.Default.Password), Password.Decrypt(Settings.Default.WebApiKey), Settings.Default.SearchFullPath, Settings.Default.ResultFullPath, Settings.Default.Email ); taskDef.Actions.Add(new ExecAction(file.FullName, args)); if (Settings.Default.RadioButtonDaily) { var dailyTrigger = new DailyTrigger { StartBoundary = DateTime.Today + TimeSpan.FromHours(8) }; taskDef.Triggers.Add(dailyTrigger); } else if (Settings.Default.RadioButtonWeekly) { var weeklyTrigger = new WeeklyTrigger(DaysOfTheWeek.Monday) { StartBoundary = DateTime.Today + TimeSpan.FromHours(8) }; taskDef.Triggers.Add(weeklyTrigger); } else if (Settings.Default.RadioButtonMonthly) { var monthlyTrigger = new MonthlyTrigger() { StartBoundary = DateTime.Today + TimeSpan.FromHours(8) }; taskDef.Triggers.Add(monthlyTrigger); } else if (Settings.Default.RadioButtonAsThe) { var counter = int.Parse(comboBoxCounter.SelectedItem.ToString()); var daysHoursCounter = comboBoxMinutesHoursDays.SelectedIndex; var asTrigger = new DailyTrigger { StartBoundary = DateTime.Now + TimeSpan.FromMinutes(5) }; switch (daysHoursCounter) { //co minutę case 0: asTrigger.Repetition.Interval = TimeSpan.FromMinutes(counter <= 10 ? 10 : counter); break; //co godzinę case 1: asTrigger.Repetition.Interval = TimeSpan.FromHours(counter); break; //co ileś tam dni case 2: asTrigger.Repetition.Interval = TimeSpan.FromDays(counter); break; } taskDef.Triggers.Add(asTrigger); } task.RootFolder.RegisterTaskDefinition("AllegroParser", taskDef); } MessageBox.Show("Utworzono zadanie w harmonogramie zadań!"); }
internal static void LongTest(TaskService ts, System.IO.TextWriter output, params string[] arg) { string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name; Version ver = ts.HighestSupportedVersion; bool isV12 = (ver >= new Version(1, 2)); bool isV13 = (ver >= new Version(1, 3)); bool isV14 = (ver >= new Version(1, 4)); output.WriteLine("Highest version: " + ver); output.WriteLine("Server: {0} ({1}); User: {2}\\{3}", ts.TargetServer, ts.Connected ? "Connected" : "Disconnected", ts.UserAccountDomain, ts.UserName); output.WriteLine("Running tasks:"); foreach (RunningTask rt in ts.GetRunningTasks(true)) { if (rt != null) { output.WriteLine("+ {0}, {1} ({2})", rt.Name, rt.Path, rt.State); if (ver.Minor > 0) output.WriteLine(" Current Action: " + rt.CurrentAction); } } string filter = arg.Length > 0 ? arg[0] : string.Empty; TaskFolder tf = ts.RootFolder; TaskCollection tasks = tf.GetTasks(new Wildcard(filter)); output.WriteLine("\nRoot folder tasks matching \"{1}\" ({0}):", tasks.Count, filter); foreach (Task t in tasks) { try { output.WriteLine("+ {0}, {1} ({2}) - {3}", t.Name, t.Definition.RegistrationInfo.Author, t.State, t.Definition.Settings.Compatibility); foreach (Trigger trg in t.Definition.Triggers) output.WriteLine(" + {0}", trg); foreach (var act in t.Definition.Actions) output.WriteLine(" = {0}", act); } catch { } } output.WriteLine("\n***Finding defrag task***"); Task ft = ts.FindTask("*defrag*"); if (ft != null) output.WriteLine("Defrag task found at " + ft.Path); else output.WriteLine("Defrag task not found."); TaskFolderCollection tfs = tf.SubFolders; if (tfs.Count > 0) { output.WriteLine("\nSub folders:"); try { foreach (TaskFolder sf in tfs) output.WriteLine("+ {0}", sf.Path); } catch (Exception ex) { output.WriteLine(ex.ToString()); } } if (isV12) { output.WriteLine("\n***Checking folder retrieval***"); try { const string testFolder = "David's TestFolder"; try { tf.CreateFolder(testFolder); } catch (System.Runtime.InteropServices.COMException cex) { if (cex.ErrorCode != -2147024713) throw; } catch { throw; } TaskFolder sub = tf.SubFolders[testFolder]; output.WriteLine("\nSubfolder path: " + sub.Path); try { ts.AddTask(testFolder + @"\MyTask", new DailyTrigger(), new ExecAction("notepad")); output.WriteLine(" - Tasks: " + sub.Tasks.Count.ToString()); sub.DeleteTask("MyTask"); } catch (Exception ex) { output.WriteLine(ex.ToString()); } tf.DeleteFolder(testFolder); } catch (NotSupportedException) { } catch (Exception ex) { output.WriteLine(ex.ToString()); } } output.WriteLine("\n***Checking task creation***"); try { TaskDefinition td = ts.NewTask(); td.Data = "Your data"; //td.Principal.UserId = "SYSTEM"; //td.Principal.LogonType = TaskLogonType.ServiceAccount; if (isV12) td.Principal.LogonType = TaskLogonType.S4U; td.RegistrationInfo.Author = "dahall"; td.RegistrationInfo.Description = "Does something"; td.RegistrationInfo.Documentation = "Don't pretend this is real."; td.Settings.DisallowStartIfOnBatteries = true; td.Settings.Enabled = false; td.Settings.ExecutionTimeLimit = TimeSpan.Zero; // FromHours(2); td.Settings.Hidden = false; td.Settings.IdleSettings.IdleDuration = TimeSpan.FromMinutes(20); td.Settings.IdleSettings.RestartOnIdle = false; td.Settings.IdleSettings.StopOnIdleEnd = false; td.Settings.IdleSettings.WaitTimeout = TimeSpan.FromMinutes(10); td.Settings.Priority = System.Diagnostics.ProcessPriorityClass.Normal; td.Settings.RunOnlyIfIdle = true; td.Settings.RunOnlyIfNetworkAvailable = true; td.Settings.StopIfGoingOnBatteries = true; if (isV12) { td.Principal.RunLevel = TaskRunLevel.Highest; //.LUA; td.Principal.Id = "Author"; td.RegistrationInfo.SecurityDescriptorSddlForm = "D:P(A;;FA;;;BA)(A;;FA;;;SY)(A;;FRFX;;;LS)"; td.RegistrationInfo.Source = "Test App"; td.RegistrationInfo.URI = "test://app"; td.RegistrationInfo.Version = new Version(0, 9); //td.Settings.AllowDemandStart = false; td.Settings.AllowHardTerminate = false; td.Settings.Compatibility = TaskCompatibility.V2; td.Settings.DeleteExpiredTaskAfter = TimeSpan.FromMinutes(1); td.Settings.MultipleInstances = TaskInstancesPolicy.StopExisting; td.Settings.StartWhenAvailable = true; td.Settings.WakeToRun = true; td.Settings.RestartCount = 5; td.Settings.RestartInterval = TimeSpan.FromSeconds(100); //td.Settings.NetworkSettings.Id = new Guid("{99AF272D-BC5B-4F64-A5B7-8688392C13E6}"); } if (isV13) { td.Settings.Compatibility = TaskCompatibility.V2_1; td.Settings.DisallowStartOnRemoteAppSession = true; td.Settings.UseUnifiedSchedulingEngine = false; /*td.Principal.ProcessTokenSidType = TaskProcessTokenSidType.Unrestricted; td.Principal.RequiredPrivileges.Add(TaskPrincipalPrivilege.SeBackupPrivilege); td.Principal.RequiredPrivileges.Add(TaskPrincipalPrivilege.SeDebugPrivilege); td.Principal.RequiredPrivileges.Add(TaskPrincipalPrivilege.SeImpersonatePrivilege); output.Write("Priv: "); //output.Write(td.Principal.RequiredPrivileges[0]); foreach (TaskPrincipalPrivilege item in td.Principal.RequiredPrivileges) output.Write(item.ToString() + ", "); output.WriteLine();*/ } if (isV14) { td.Settings.Compatibility = TaskCompatibility.V2_2; td.Settings.Volatile = true; if (td.Principal.LogonType == TaskLogonType.ServiceAccount) { td.Settings.MaintenanceSettings.Exclusive = true; td.Settings.MaintenanceSettings.Period = TimeSpan.FromDays(5); td.Settings.MaintenanceSettings.Deadline = TimeSpan.FromDays(15); } } // Setup Triggers if (isV12) { BootTrigger bTrigger = (BootTrigger)td.Triggers.Add(new BootTrigger { Enabled = false }); //(BootTrigger)td.Triggers.AddNew(TaskTriggerType.Boot); if (isV12) bTrigger.Delay = TimeSpan.FromMinutes(5); } DailyTrigger dTrigger = (DailyTrigger)td.Triggers.Add(new DailyTrigger { DaysInterval = 2 }); if (isV12) dTrigger.RandomDelay = TimeSpan.FromHours(2); if (isV12) { EventTrigger eTrigger = (EventTrigger)td.Triggers.Add(new EventTrigger()); eTrigger.Subscription = "<QueryList><Query Id=\"0\" Path=\"Security\"><Select Path=\"Security\">*[System[Provider[@Name='VSSAudit'] and EventID=25]]</Select></Query></QueryList>"; eTrigger.ValueQueries.Add("Name", "Value"); td.Triggers.Add(new RegistrationTrigger { Delay = TimeSpan.FromMinutes(5) }); td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.ConsoleConnect, UserId = user }); td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.ConsoleDisconnect }); td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.RemoteConnect }); td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.RemoteDisconnect }); td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.SessionLock, UserId = user }); td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.SessionUnlock }); } td.Triggers.Add(new IdleTrigger()); LogonTrigger lTrigger = (LogonTrigger)td.Triggers.Add(new LogonTrigger()); if (isV12) { lTrigger.Delay = TimeSpan.FromMinutes(15); lTrigger.UserId = user; lTrigger.Repetition.Interval = TimeSpan.FromSeconds(1000); } MonthlyTrigger mTrigger = (MonthlyTrigger)td.Triggers.Add(new MonthlyTrigger()); mTrigger.DaysOfMonth = new int[] { 3, 6, 10, 18 }; mTrigger.MonthsOfYear = MonthsOfTheYear.July | MonthsOfTheYear.November; if (isV12) mTrigger.RunOnLastDayOfMonth = true; mTrigger.EndBoundary = DateTime.Today + TimeSpan.FromDays(90); MonthlyDOWTrigger mdTrigger = (MonthlyDOWTrigger)td.Triggers.Add(new MonthlyDOWTrigger()); mdTrigger.DaysOfWeek = DaysOfTheWeek.AllDays; mdTrigger.MonthsOfYear = MonthsOfTheYear.January | MonthsOfTheYear.December; if (isV12) mdTrigger.RunOnLastWeekOfMonth = true; mdTrigger.WeeksOfMonth = WhichWeek.FirstWeek; TimeTrigger tTrigger = (TimeTrigger)td.Triggers.Add(new TimeTrigger()); tTrigger.StartBoundary = DateTime.Now + TimeSpan.FromMinutes(1); tTrigger.EndBoundary = DateTime.Today + TimeSpan.FromDays(7); if (isV12) tTrigger.ExecutionTimeLimit = TimeSpan.FromSeconds(19); if (isV12) tTrigger.Id = "Time test"; tTrigger.Repetition.Duration = TimeSpan.FromMinutes(21); tTrigger.Repetition.Interval = TimeSpan.FromMinutes(17); tTrigger.Repetition.StopAtDurationEnd = true; WeeklyTrigger wTrigger = (WeeklyTrigger)td.Triggers.Add(new WeeklyTrigger()); wTrigger.DaysOfWeek = DaysOfTheWeek.Monday; wTrigger.WeeksInterval = 3; // Setup Actions td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null)); if (isV12) { td.Actions.Context = "Author"; if (td.Principal.LogonType == TaskLogonType.InteractiveToken || td.Principal.LogonType == TaskLogonType.Group || td.Principal.LogonType == TaskLogonType.S4U) td.Actions.Add(new ShowMessageAction("Running Notepad", "Info")); td.Actions.Add(new EmailAction("Testing", "*****@*****.**", "*****@*****.**", "You've got mail.", "mail.myisp.com") { Id = "Email", Attachments = new object[] { (string)new TemporaryScopedFile() } }); var email = (EmailAction)td.Actions["Email"]; email.HeaderFields.Add("Precedence", "bulk"); td.Actions.Add(new ComHandlerAction(new Guid("{BF300543-7BA5-4C17-A318-9BBDB7429A21}"), @"C:\Users\dahall\Documents\Visual Studio 2010\Projects\TaskHandlerProxy\TaskHandlerSample\bin\Release\TaskHandlerSample.dll|TaskHandlerSample.TaskHandler|MoreData")); } // Validate and Register task WriteXml(td, "PreRegTest"); td.Validate(true); Task t = tf.RegisterTaskDefinition("Test", td); WriteXml(t); // Try copying it TaskDefinition td2 = ts.NewTask(); foreach (Trigger tg in td.Triggers) td2.Triggers.Add((Trigger)tg.Clone()); foreach (Microsoft.Win32.TaskScheduler.Action a in td.Actions) td2.Actions.Add((Microsoft.Win32.TaskScheduler.Action)a.Clone()); tf.RegisterTaskDefinition("Test2", td2, TaskCreation.CreateOrUpdate, user, null, TaskLogonType.InteractiveToken, null); tf.DeleteTask("Test2"); } catch (Exception ex) { output.WriteLine(ex.ToString()); return; } // Display results Task runningTask = tf.Tasks["Test"]; output.WriteLine("\nNew task will next run at " + runningTask.NextRunTime); DateTime[] times = runningTask.GetRunTimes(DateTime.Now, DateTime.Now + TimeSpan.FromDays(7), 0); if (times.Length > 0) { output.WriteLine("\nNew task will run at the following times over the next week:"); foreach (DateTime dt in times) output.WriteLine(" {0}", dt); } output.WriteLine("\nNew task triggers:"); for (int i = 0; i < runningTask.Definition.Triggers.Count; i++) output.WriteLine(" {0}: {1}", i, runningTask.Definition.Triggers[i]); output.WriteLine("\nNew task actions:"); for (int i = 0; i < runningTask.Definition.Actions.Count; i++) output.WriteLine(" {0}: {1}", i, runningTask.Definition.Actions[i]); // Loop through event logs for this task and find action completed events newest to oldest if (isV12) { output.WriteLine("\nTask history enumeration:"); TaskEventLog log = new TaskEventLog(@"\Maint", new int[] { 201 }, DateTime.Now.AddDays(-7)) { EnumerateInReverse = false }; foreach (TaskEvent ev in log) output.WriteLine(" Completed action '{0}' ({2}) at {1}.", ev.GetDataValue("ActionName"), ev.TimeCreated.Value, ev.GetDataValue("ResultCode")); } DisplayTask(runningTask, true); tf.DeleteTask("Test"); }
public static bool IsTaskInstalled(string name) { using (var ts = new Scheduler.TaskService()) return(ts.FindTask(name) != null); }
public static bool StartupTaskExists() { using (TaskService _taskService = new TaskService()) { Task _task = _taskService.FindTask(Constants.Generic.TASKNAME); if (_task == null) { return false; } ExecAction _action = _task.Definition.Actions.OfType<ExecAction>().FirstOrDefault(); if (_action == null || _action.Path != Assembly.GetExecutingAssembly().Location) { return false; } return true; } }
/// <summary> /// Fills Windows Task details according to the current UI state /// </summary> void FillTaskDetail() { try { TaskService service = new TaskService(); Task task = null; task = service.FindTask("PCCleaner1ClickMaint"); if (task != null) { chkSat.Checked = chkSun.Checked = chkMon.Checked = chkTue.Checked = chkWed.Checked = chkThu.Checked = chkFri.Checked = false; foreach (Trigger trg in task.Definition.Triggers) { timePicker.Value = trg.StartBoundary; if ( trg.TriggerType == TaskTriggerType.Daily || (trg.TriggerType == TaskTriggerType.Weekly && (trg as WeeklyTrigger).DaysOfWeek == DaysOfTheWeek.AllDays) ) { cmbSelectSchedule.SelectedIndex = (int)Schedule.Daily; nudDays.Value = (trg as DailyTrigger).DaysInterval; } else if (trg.TriggerType == TaskTriggerType.Weekly) { cmbSelectSchedule.SelectedIndex = (int)Schedule.Weekly; WeeklyTrigger wTrigger = (trg as WeeklyTrigger); nudWeeks.Value = wTrigger.WeeksInterval; if (wTrigger.DaysOfWeek == DaysOfTheWeek.Monday) { chkMon.Checked = true; } if (wTrigger.DaysOfWeek == DaysOfTheWeek.Tuesday) { chkTue.Checked = true; } if (wTrigger.DaysOfWeek == DaysOfTheWeek.Wednesday) { chkWed.Checked = true; } if (wTrigger.DaysOfWeek == DaysOfTheWeek.Thursday) { chkThu.Checked = true; } if (wTrigger.DaysOfWeek == DaysOfTheWeek.Friday) { chkFri.Checked = true; } if (wTrigger.DaysOfWeek == DaysOfTheWeek.Saturday) { chkSat.Checked = true; } if (wTrigger.DaysOfWeek == DaysOfTheWeek.Sunday) { chkSun.Checked = true; } } else if (trg.TriggerType == TaskTriggerType.Monthly || trg.TriggerType == TaskTriggerType.MonthlyDOW) { cmbSelectSchedule.SelectedIndex = (int)Schedule.Monthly; if (trg.TriggerType == TaskTriggerType.Monthly) { radDay.Checked = true; nudDayMonth.Value = (trg as MonthlyTrigger).DaysOfMonth[0]; } else { radMonth.Checked = true; MonthlyDOWTrigger mdTrigger = trg as MonthlyDOWTrigger; if (mdTrigger.DaysOfWeek == DaysOfTheWeek.Monday) { cmbday.SelectedIndex = (int)DayOfWeek.Monday; } if (mdTrigger.DaysOfWeek == DaysOfTheWeek.Tuesday) { cmbday.SelectedIndex = (int)DayOfWeek.Tuesday; } if (mdTrigger.DaysOfWeek == DaysOfTheWeek.Wednesday) { cmbday.SelectedIndex = (int)DayOfWeek.Wednesday; } if (mdTrigger.DaysOfWeek == DaysOfTheWeek.Thursday) { cmbday.SelectedIndex = (int)DayOfWeek.Thursday; } if (mdTrigger.DaysOfWeek == DaysOfTheWeek.Friday) { cmbday.SelectedIndex = (int)DayOfWeek.Friday; } if (mdTrigger.DaysOfWeek == DaysOfTheWeek.Saturday) { cmbday.SelectedIndex = (int)DayOfWeek.Saturday; } if (mdTrigger.DaysOfWeek == DaysOfTheWeek.Sunday) { cmbday.SelectedIndex = (int)DayOfWeek.Sunday; } if (mdTrigger.WeeksOfMonth == WhichWeek.FirstWeek) { cmbweek.SelectedIndex = 0; } if (mdTrigger.WeeksOfMonth == WhichWeek.SecondWeek) { cmbweek.SelectedIndex = 1; } if (mdTrigger.WeeksOfMonth == WhichWeek.ThirdWeek) { cmbweek.SelectedIndex = 2; } if (mdTrigger.WeeksOfMonth == WhichWeek.FourthWeek) { cmbweek.SelectedIndex = 3; } if (mdTrigger.WeeksOfMonth == WhichWeek.LastWeek) { cmbweek.SelectedIndex = 4; } } } else if (trg.TriggerType == TaskTriggerType.Time) { cmbSelectSchedule.SelectedIndex = (int)Schedule.Once; timePickerOnce.Value = trg.StartBoundary; } else if (trg.TriggerType == TaskTriggerType.Logon) { cmbSelectSchedule.SelectedIndex = (int)Schedule.AtLogon; } else if (trg.TriggerType == TaskTriggerType.Boot) { cmbSelectSchedule.SelectedIndex = (int)Schedule.AtSystemStartUp; } else if (trg.TriggerType == TaskTriggerType.Idle) { cmbSelectSchedule.SelectedIndex = (int)Schedule.WhenIdel; nudMinutes.Value = trg.StartBoundary.Minute; } } ChangeSettings(); } } catch { } }
static void updateTask(string _taskguid, string _job) { using (TaskService ts = new TaskService()) { var _task = ts.FindTask("KNXTask" + _job + _taskguid, true); bool _taskExists = (_task != null); if(_taskExists){ _task.Enabled = false; if (_task.State == TaskState.Running) { _task.Stop(); } } var _taskPing = ts.FindTask("KNXTaskPing" + _job + _taskguid, true); bool _taskPingExists = (_taskPing != null); if (_taskPingExists) { _taskPing.Enabled = false; if (_taskPing.State == TaskState.Running) { _taskPing.Stop(); } } } }
public void WhenTheIsExecutedTimes(string scheduleName, int times) { try { int i = 0; var x = new TaskService(); x.GetFolder("Warewolf"); var task = x.FindTask(scheduleName); do { task.Run(); const int TimeOut = 10; int time = 0; while(task.State == TaskState.Running && time < TimeOut) { time++; Thread.Sleep(1000); } i++; } while(i < times); } catch(Exception e) { ScenarioContext.Current["Error"] = e; } }
/// <summary> /// The remove task. /// </summary> /// <param name="taskName"> /// The task name. /// </param> /// <param name="service"> /// The service. /// </param> private void RemoveTask(string taskName, TaskService service) { Task existTask = service.FindTask(taskName, false); if (existTask != null) { service.RootFolder.DeleteTask(taskName); } }
private void LoadTaskSettings(WindowsIdentity currentIdentity) { using (WinTasks.TaskService ts = new WinTasks.TaskService()) { chkStartWithWindows.Checked = false; chkStartWithWindows.Enabled = true; radStartForCurrentUser.Checked = false; radStartForAllUsers.Checked = false; WinTasks.Task task = ts.FindTask(Application.ProductName, false); if (task == null) { pnlStartupOptions.Enabled = false; } else { WinTasks.Trigger trigger = task.Definition.Triggers.First(); if (trigger != null && trigger.TriggerType == WinTasks.TaskTriggerType.Logon) { WinTasks.LogonTrigger logonTrigger = (WinTasks.LogonTrigger)trigger; if (logonTrigger.UserId == null) { radStartForAllUsers.Checked = true; chkStartWithWindows.Checked = true; } else if (string.Equals(logonTrigger.UserId, currentIdentity.Name, StringComparison.InvariantCultureIgnoreCase) || string.Equals(logonTrigger.UserId, currentIdentity.User.Value, StringComparison.InvariantCultureIgnoreCase)) { radStartForCurrentUser.Checked = true; chkStartWithWindows.Checked = true; } else { chkStartWithWindows.Checked = true; chkStartWithWindows.Enabled = false; pnlStartupOptions.Enabled = false; } } pnlStartupOptions.Enabled = true; } if (!new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)) { SendMessage(btnOK.Handle, BCM_SETSHIELD, 0, (IntPtr)(radStartForAllUsers.Checked ? 1 : 0)); } } }
private void setScheduledEvents() { using (TaskService taskService = new TaskService()) { // Delete old task if it exists if (taskService.FindTask("Wallpaper Setter") != null) { taskService.RootFolder.DeleteTask("Wallpaper Setter"); } // Define the trigger Trigger trigger; if (frequencyDdl.Text.Equals("Hour") || frequencyDdl.Text.Equals("Minute")) { // Run either every hour or every minute from registration trigger = new RegistrationTrigger(); if (frequencyDdl.Text.Equals("Hour")) { trigger.Repetition = new RepetitionPattern(new TimeSpan(1, 0, 0), TimeSpan.Zero); } else { trigger.Repetition = new RepetitionPattern(new TimeSpan(0, 1, 0), TimeSpan.Zero); } } else { // If they specify daily, or don't specify a frequency, run every day at 6 am // TODO make that time configurable DateTime now = DateTime.Now; DateTime next = now.Date.AddHours(24 + 6); next = next.AddDays((now - next).Days); trigger = new DailyTrigger(); trigger.StartBoundary = next; } // Define the task TaskDefinition newTask = taskService.NewTask(); newTask.RegistrationInfo.Description = "Wallpaper Setter"; newTask.Triggers.Add(trigger); newTask.Actions.Add(new ExecAction(utilPath, workingDirectory: Directory.GetCurrentDirectory())); newTask.Settings.Enabled = true; taskService.RootFolder.RegisterTaskDefinition("Wallpaper Setter", newTask); // Registration triggers get run automatically when created. But other types don't, so run manually if needed. if (newTask.Triggers[0].TriggerType != TaskTriggerType.Registration) { taskService.RootFolder.Tasks["Wallpaper Setter"].Run(); } } }