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 void AddTask(int min, int hour, bool restart) { var taskService = new TaskService(); //Create task definition var taskDefinition = taskService.NewTask(); taskDefinition.RegistrationInfo.Description = min + "@" + hour + "@" + ((restart) ? "r" : "s"); taskDefinition.Principal.UserId = "SYSTEM"; var trigger = new DailyTrigger { StartBoundary = DateTime.Today + TimeSpan.FromHours(hour) + TimeSpan.FromMinutes(min) }; taskDefinition.Triggers.Add(trigger); //Create task action var fileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"Power.exe"); taskDefinition.Actions.Add(restart ? new ExecAction(fileName, "reboot \"This computer is going to reboot.\"") : new ExecAction(fileName, "shutdown \"This computer is going to shutdown to save power.\"")); taskDefinition.Settings.AllowDemandStart = false; taskDefinition.Settings.DisallowStartIfOnBatteries = false; taskDefinition.Settings.DisallowStartOnRemoteAppSession = false; taskDefinition.Settings.StopIfGoingOnBatteries = false; taskService.RootFolder.RegisterTaskDefinition(@"FOG\" + taskDefinition.RegistrationInfo.Description, taskDefinition); taskService.Dispose(); }
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; }
public static void modifyTask(DailyTrigger dt) { using (TaskService ts = new TaskService()) { Task t = ts.GetTask("taxiService"); TaskDefinition td = t.Definition; td.Triggers.Add(dt); ts.RootFolder.RegisterTaskDefinition(@"taxiService", td); } }
public void CreateTask(TaskService service) { var path = Application.StartupPath; try { var task = service.AddTask("SP_Field_Monitor", new DailyTrigger() { StartBoundary = DateTime.Parse("10:00:00 AM") }, new ExecAction(path + "\\SPFieldMonitor.exe", "-user [email protected] -password \"!thisisatestitisonlyatest!\"", path), "SYSTEM"); var trigger = new DailyTrigger() { StartBoundary = DateTime.Parse("11:00:00 AM") }; trigger.Repetition.Duration = TimeSpan.FromHours(22); trigger.Repetition.Interval = TimeSpan.FromHours(1); var checkTask = service.AddTask("SP_Field_Monitor_Check", trigger, new ExecAction(path + "\\SPFieldMonitor.exe", "-user [email protected] -password \"!thisisatestitisonlyatest!\" -check", path), "SYSTEM"); MessageBox.Show( "The daily task has been scheduled.\nIf you move any of the Field Monitor executables, you will need to click this button again to reschedule the task.", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } catch (UnauthorizedAccessException) { MessageBox.Show( "You need administrator privileges to schedule this task. Try running the program as an administrator.", "Insufficient Access Rights", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
TaskDefinition CreateTask(TaskService taskService, String taskName, TimeSpan RetryIntervall) { DailyTrigger dailyTrigger = new DailyTrigger(); dailyTrigger.StartBoundary = DateTime.Now.Date; //dailyTrigger.EndBoundary = DateTime.MaxValue; //dailyTrigger.ExecutionTimeLimit = TimeSpan.MaxValue; dailyTrigger.Repetition.Interval = RetryIntervall; TaskDefinition taskDefinition = taskService.NewTask(); taskDefinition.Triggers.Add(dailyTrigger); LogonTrigger logonTrigger = new LogonTrigger(); taskDefinition.Triggers.Add(logonTrigger); taskDefinition.Principal.RunLevel = TaskRunLevel.Highest; taskDefinition.Principal.UserId = "WPMedia\\WPProduction"; return taskDefinition; }
public void TaskShedulerWrapper_Dev2RepetitionPattern_Construct() { Trigger a = new DailyTrigger(6); var native = a.Repetition; a.Repetition.Duration = new TimeSpan(2); a.Repetition.Interval = new TimeSpan(3); a.Repetition.StopAtDurationEnd = true; var patt = new Dev2RepetitionPattern(a.Repetition); Assert.AreEqual(patt.Duration,native.Duration); Assert.AreEqual(patt.Interval,native.Interval); Assert.AreEqual(patt.StopAtDurationEnd, native.StopAtDurationEnd); Assert.AreEqual(patt.IsSet(),native.IsSet()); native.Dispose(); }
static void startSchedule(DailyTrigger dt) { using (TaskService ts = new TaskService()) { TaskDefinition td = ts.NewTask(); td.RegistrationInfo.Description = "Start Taxi Service"; td.Triggers.Add(dt); string appPath = Path.GetDirectoryName(Application.ExecutablePath); td.Actions.Add(new ExecAction(appPath+@"\emails.exe", "c:\\test.log", null)); string d = dt.StartBoundary.TimeOfDay.ToString(); //string nd= d.Replace(':', 'T'); ts.RootFolder.RegisterTaskDefinition(@"taxiService", td); // Remove the task we just created // ts.RootFolder.DeleteTask("Test"); } }
/// <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 { } }
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ń!"); }
void UpdateTrigger(IScheduledResource task, Table table) { var sched = table.Rows[0]["ScheduleType"]; Trigger x; switch(sched) { case "At log on": x = new LogonTrigger(); break; case "On a schedule": x = CreateScheduleTrigger(table); break; case "At Startup": x = new BootTrigger(); break; case "On Idle": x = new IdleTrigger(); break; default: x = new DailyTrigger(); break; } task.Trigger.Trigger = new Dev2Trigger(new TaskServiceConvertorFactory(), x); }
public void TestDailySelect() { var span1 = new DailyTrigger { StartBoundary = DateTime.Parse("12/7/2014 6:00 PM") }; var r = span1.SelectDates(x => x).Take(3).ToArray(); Debug.Assert(r.Length == 3); Debug.Assert(r[0].Date == DateTime.Today); Debug.Assert(r[0].TimeOfDay == new TimeSpan(18, 0, 0)); Debug.Assert(r[1].Date == r[0].Date.AddDays(1)); Debug.Assert(r[1].TimeOfDay == new TimeSpan(18, 0, 0)); Debug.Assert(r[2].Date == r[1].Date.AddDays(1)); Debug.Assert(r[2].TimeOfDay == new TimeSpan(18, 0, 0)); // repeat interval span1.Repetition.Interval = new TimeSpan(1, 0, 0); span1.Repetition.Duration = new TimeSpan(3, 0, 0); r = span1.SelectDates(x => x).Take(6).ToArray(); Debug.Assert(r.Length == 6); Debug.Assert(r[0].Date == DateTime.Today); Debug.Assert(r[0].TimeOfDay == new TimeSpan(18, 0, 0)); Debug.Assert(r[1].Date == r[0].Date); Debug.Assert(r[1].TimeOfDay == new TimeSpan(19, 0, 0)); Debug.Assert(r[2].Date == r[1].Date); Debug.Assert(r[2].TimeOfDay == new TimeSpan(20, 0, 0)); Debug.Assert(r[3].Date == r[2].Date.AddDays(1)); Debug.Assert(r[3].TimeOfDay == new TimeSpan(18, 0, 0)); Debug.Assert(r[4].Date == r[3].Date); Debug.Assert(r[4].TimeOfDay == new TimeSpan(19, 0, 0)); Debug.Assert(r[5].Date == r[4].Date); Debug.Assert(r[5].TimeOfDay == new TimeSpan(20, 0, 0)); // end boundry span1.EndBoundary = DateTime.Today.AddDays(1).AddHours(19); r = span1.SelectDates(x => x).Take(6).ToArray(); Debug.Assert(r.Length == 5); Debug.Assert(r[0].Date == DateTime.Today); Debug.Assert(r[0].TimeOfDay == new TimeSpan(18, 0, 0)); Debug.Assert(r[1].Date == r[0].Date); Debug.Assert(r[1].TimeOfDay == new TimeSpan(19, 0, 0)); Debug.Assert(r[1].Date == r[1].Date); Debug.Assert(r[2].TimeOfDay == new TimeSpan(20, 0, 0)); Debug.Assert(r[3].Date == r[2].Date.AddDays(1)); Debug.Assert(r[3].TimeOfDay == new TimeSpan(18, 0, 0)); Debug.Assert(r[4].Date == r[3].Date); Debug.Assert(r[4].TimeOfDay == new TimeSpan(19, 0, 0)); // every other week span1.EndBoundary = DateTime.MaxValue; span1.DaysInterval = 2; for (var i = 0; i < 2; i++) { r = span1.SelectDates(x => x, DateTime.Today.AddDays(i)).Take(5).ToArray(); Debug.Assert(r.Length == 5); Debug.Assert(r[0].Date.Day % 2 == 1); Debug.Assert(r[0].TimeOfDay == new TimeSpan(18, 0, 0)); Debug.Assert(r[1].Date == r[0].Date); Debug.Assert(r[1].TimeOfDay == new TimeSpan(19, 0, 0)); Debug.Assert(r[2].Date == r[1].Date); Debug.Assert(r[2].TimeOfDay == new TimeSpan(20, 0, 0)); Debug.Assert(r[3].Date == r[2].Date.AddDays(2)); Debug.Assert(r[3].TimeOfDay == new TimeSpan(18, 0, 0)); Debug.Assert(r[4].Date == r[3].Date); Debug.Assert(r[4].TimeOfDay == new TimeSpan(19, 0, 0)); } }
//Scheduled Activities public string createScheduleactivities(string daily, int recurdays, string date, string time, string weekdays, string monthdays) { string schedulerName = ""; try { if (ConfigSettings.ClientName.ToUpper() == clientName) { schedulerName = "ActiveiPCOptimizationScheduler"; } else { schedulerName = "GearHeadConnectPCOptimizationScheduler"; } RegistryKey UninstallRegistryKey = GetUninstallRegistryKeyByProductName(ConfigSettings.ClientName); String uninstallPath = UninstallRegistryKey.GetValue("UninstallString").ToString(); String backupSchedulerPath = Path.Combine(uninstallPath.Replace("\"", "").Substring(0, uninstallPath.LastIndexOf("\\")), ConfigurationManager.AppSettings["PCOptimizationConsole"]); TaskService ts = new TaskService(); TaskCollection taskCollection = ts.RootFolder.GetTasks(new System.Text.RegularExpressions.Regex(schedulerName)); if (taskCollection != null && taskCollection.Count > 0) { ts.RootFolder.DeleteTask(taskCollection[0].Name); } TaskDefinition td = ts.NewTask(); td.RegistrationInfo.Description = schedulerName; Int16 days = Convert.ToInt16(recurdays); //DateTime combinedDate = Convert.ToDateTime(date + " " + time,new CultureInfo("en-US")); //DateTime combinedDate1 = Convert.ToDateTime("Apr-30-2015 02:12 PM",new CultureInfo("en-US")); //DateTime combinedDate2 = Convert.ToDateTime("04-30-2015 02:12 PM", new CultureInfo("en-US")); //DateTime combinedDate = Convert.ToDateTime(date + " " + time, new CultureInfo("en-GB",true)); //string dateFormat = CultureInfo.CurrentUICulture.DateTimeFormat.LongDatePattern; ////string dt = "04/30/2015 02:12:00 PM"; //string dt = date + " "+time; //IFormatProvider culture = new System.Globalization.CultureInfo("en-US", true); //DateTime combinedDate = DateTime.Parse(dt, culture, DateTimeStyles.AssumeLocal); string dateString = date + " " + time; string format = "MM/dd/yyyy h:mm tt"; DateTime combinedDate = DateTime.ParseExact(dateString, format,CultureInfo.InvariantCulture); if (daily == "onetime") { td.Triggers.Add(new TimeTrigger(combinedDate)); } if (daily == "daily") { DailyTrigger dailyTrigger = new DailyTrigger(days); dailyTrigger.StartBoundary = combinedDate; td.Triggers.Add(dailyTrigger); } if (daily == "weekly") { days = Convert.ToInt16(recurdays); string[] strArray = weekdays.Split(','); foreach (string item in strArray) { DaysOfTheWeek daysofWeek = (DaysOfTheWeek)Enum.Parse(typeof(DaysOfTheWeek), item); WeeklyTrigger weekTrigger = new WeeklyTrigger(daysofWeek, days); weekTrigger.StartBoundary = combinedDate; td.Triggers.Add(weekTrigger); } } if (daily == "monthly") { MonthlyTrigger monthlyTrigger = new MonthlyTrigger(); //MonthsOfTheYear selectedMonth= ((MonthsOfTheYear)Convert.ToInt32(monthdays)); monthlyTrigger.MonthsOfYear = MonthsOfTheYear.AllMonths; //monthlyTrigger.MonthsOfYear = (monthdays == "01") ? MonthsOfTheYear.January : (monthdays == "02") ? MonthsOfTheYear.February : (monthdays == "03") ? MonthsOfTheYear.March : (monthdays == "04") ? MonthsOfTheYear.April : (monthdays == "05") ? MonthsOfTheYear.May : (monthdays == "06") ? MonthsOfTheYear.June : (monthdays == "07") ? MonthsOfTheYear.July : (monthdays == "08") ? MonthsOfTheYear.August : (monthdays == "09") ? MonthsOfTheYear.September : (monthdays == "10") ? MonthsOfTheYear.October : (monthdays == "11") ? MonthsOfTheYear.November : MonthsOfTheYear.December; //monthlyTrigger.MonthsOfYear = (mon == "01") ? MonthsOfTheYear.January : (mon == "02") ? MonthsOfTheYear.February : (mon == "03") ? MonthsOfTheYear.March : (mon == "04") ? MonthsOfTheYear.April : (mon == "05") ? MonthsOfTheYear.May : (mon == "06") ? MonthsOfTheYear.June : (mon == "07") ? MonthsOfTheYear.July : (mon == "08") ? MonthsOfTheYear.August : (mon == "09") ? MonthsOfTheYear.September : (mon == "10") ? MonthsOfTheYear.October : (mon == "11") ? MonthsOfTheYear.November : MonthsOfTheYear.December; // monthlyTrigger.MonthsOfYear = (MonthsOfTheYear)Enum.Parse(typeof(MonthsOfTheYear), monthdays); monthlyTrigger.StartBoundary = combinedDate; //foreach (var day in monthdays) //{ // daysList.Add(Convert.ToInt16(day)); //} List<int> daysList = new List<int>(); foreach (var mon in monthdays.Split(',')) { daysList.Add(Convert.ToInt16(mon)); } monthlyTrigger.DaysOfMonth = daysList.ToArray(); td.Triggers.Add(monthlyTrigger); } td.Actions.Add(new ExecAction(backupSchedulerPath, null)); ts.RootFolder.RegisterTaskDefinition(schedulerName, td); return "PC Optimization scheduled successfully !!"; //GearHeadMessageBox.Instance.Show("PC Optimization scheduled successfully", "Active-I", MessageBoxButtons.OK, MessageBoxIcon.Information, GearHeadMessageBox.ModuleEnum.Router); } catch (Exception ex) { ErrorTracker.WriteErrorLog("PCOptimizaton.cs", "createScheduleactivities", "", ex.Message, ex.StackTrace, "ERROR"); return "Failed"; } }
private void schedOneRadio_CheckedChanged(object sender, EventArgs e) { if (((RadioButton)sender).Checked) { Trigger newTrigger = null; if (sender == schedOneRadio) { schedTabControl.SelectedTab = oneTimeTab; if (!onAssignment) newTrigger = new TimeTrigger(); } else if (sender == schedDailyRadio) { schedTabControl.SelectedTab = dailyTab; if (!onAssignment) newTrigger = new DailyTrigger(); } else if (sender == schedWeeklyRadio) { schedTabControl.SelectedTab = weeklyTab; if (!onAssignment) newTrigger = new WeeklyTrigger(); } else if (sender == schedMonthlyRadio) { schedTabControl.SelectedTab = monthlyTab; monthlyTriggerUI1_TriggerTypeChanged(this, EventArgs.Empty); } if (newTrigger != null && !onAssignment) { if (trigger != null) newTrigger.CopyProperties(trigger); this.Trigger = newTrigger; } } }
private void scheduleNextTask() { using (TaskService ts = new TaskService()) { TaskDefinition td = ts.NewTask(); td.RegistrationInfo.Description = "Automatically updates selected Git repositories."; DailyTrigger timeToUpdateRepositories = new DailyTrigger(); timeToUpdateRepositories.Repetition.Interval = TimeSpan.FromHours(Settings.Default.FrequencySelector); td.Triggers.Add(timeToUpdateRepositories); td.Actions.Add(new ExecAction(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)+"\\GitUpdater.exe", null, null)); ts.RootFolder.RegisterTaskDefinition(@"GitUpdater", td); } }
public string AddDailyTrigger(DateTime startTime, int everyMinute = -1) { DailyTrigger dt = new DailyTrigger(); if (everyMinute != -1) { dt.Repetition.Interval = TimeSpan.FromMinutes(everyMinute); } dt.StartBoundary = startTime; taskDef.Triggers.Add(dt); triggers.Add(dt); task.RootFolder.RegisterTaskDefinition(this.taskName, taskDef, TaskCreation.CreateOrUpdate, null, null, TaskLogonType.InteractiveToken, null); return "Added"; }
private void Runbutton_Click(object sender, EventArgs e) { if ((((this.connectForm.getConnection) || (this.connectForm.getConnection2)))) { string path2 = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)+"\\CurrentFile.txt"; string path =(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName +@"\sqlBackup\ScheduleFile\"); StreamWriter write = new StreamWriter(path2); write.Write(path); write.Close(); try { int selectedDbNum = DatabasesCheckedListBox.CheckedItems.Count; //array with selected databases number length, for store all selected databases string[] dbForBackup = new string[selectedDbNum]; //get names of selected databases int i = 0; foreach (object itemChecked in DatabasesCheckedListBox.CheckedItems) { dbForBackup[i] = itemChecked.ToString(); i++; } if (SchedulecheckBox.Checked) { TimeSpan time = ScheduleTime.Value.TimeOfDay; if (this.connectForm.getConnection) { saveschedulefile = new Save(time, this.connectForm.getHostname, this.connectForm.getPort, connectForm.getUsername, connectForm.getPassword, this.FTPHost, this.FTPusername, this.FTPpasswd, emailtextBox.Text, dbForBackup); saveschedulefile.ScheduleFile(schedulefile); ErrorScheduleLabel.Text = "Schedule completed sucessfully"; } else if (this.connectForm.getConnection2) { saveschedulefile = new Save(time, this.connectForm.getHostname2, this.connectForm.getPort2, this.connectForm.getUsername2, this.connectForm.getPassword2, this.FTPHost, this.FTPusername, this.FTPpasswd, emailtextBox.Text, dbForBackup); saveschedulefile.ScheduleFile(schedulefile); ErrorScheduleLabel.Text = "Schedule completed sucessfully"; } } } catch (Exception x) { ErrorScheduleLabel.Text = "Choose a database first"; } try { //MessageBox.Show(Convert.ToString(IsUserAdministrator())); TimeSpan time = ScheduleTime.Value.TimeOfDay; using (TaskService ts = new TaskService()) { TaskDefinition td = ts.NewTask(); //δημηουργια ονοματος και description για το schedule td.RegistrationInfo.Description = "This task will backup the database that the user has chosen "; td.Principal.DisplayName = "sqlBckup" + counter; td.Principal.RunLevel = TaskRunLevel.Highest; //δημιουργια triiger ο οποίος θα τρέχει κάθε μέρα DailyTrigger dt = new DailyTrigger(); dt.StartBoundary = DateTime.Today + TimeSpan.FromHours(Convert.ToDouble(time.Hours)) + TimeSpan.FromMinutes(Convert.ToDouble(time.Minutes)); dt.DaysInterval = 1; dt.Enabled = true; td.Triggers.Add(dt); //προσθεση ρυθμiσeων για το πως θα τρέχει το schedule td.Settings.MultipleInstances = TaskInstancesPolicy.Parallel; td.Settings.ExecutionTimeLimit = TimeSpan.FromHours(23); td.Settings.DisallowStartIfOnBatteries = false; td.Settings.WakeToRun = true; td.Settings.Hidden = true; td.Settings.StartWhenAvailable = true; td.Settings.Priority = ProcessPriorityClass.High; //προσθηκη exe action που δείχνει πιο exe θα τρεχει οταν ερθει η ωρα του schedule td.Actions.Add(new ExecAction(schedulerexe, null, null)); //ExecAction et = new ExecAction(schedulerexe, null, null); //td.Actions.Add(et); //δημιουργία του schedule ts.RootFolder.RegisterTaskDefinition("sqlBackup" + counter, td); counter++; ErrorScheduleLabel.Text = "Schedule sucessfull created"; } } catch (Exception exk) { MessageBox.Show(exk.Source); MessageBox.Show(exk.Message); MessageBox.Show(exk.StackTrace); } } }
public void SchedulerViewModel_TriggerEquals_NotEquals_ExpectFalse() { //------------Setup for test-------------------------- // ReSharper disable UseObjectOrCollectionInitializer DailyTrigger t = new DailyTrigger(); t.StartBoundary = new DateTime(2014, 01, 01); DailyTrigger t2 = new DailyTrigger(); t2.StartBoundary = new DateTime(2015, 01, 01); // ReSharper restore UseObjectOrCollectionInitializer //------------Execute Test--------------------------- //------------Assert Results------------------------- Assert.IsFalse(SchedulerViewModel.TriggerEquals(t, t2)); }
public void TaskShedulerWrapper_Dev2DailyTrigger_Construct_Test() { var native = new DailyTrigger(3); Dev2DailyTrigger wrapped = new Dev2DailyTrigger(_taskServiceConvertorFactory.Object, native); wrapped.DaysInterval = 1; Assert.AreEqual(wrapped.DaysInterval, native.DaysInterval); Assert.AreEqual(wrapped.RandomDelay, native.RandomDelay); }
private static bool SaveTask(string pathToOutputFolder, string pathToLogFile, string description, bool shutdownAfterBackup, DateTime startTask, int intervalCout, string scheduleType, bool repeatTask, string fullUserName, string password, bool usePermission, bool addingTimestampToPst, bool copyMSOutlookRegistrySettings) { bool result = false; string pathToProgram = ConfigurationManager.AppSettings["pathToBackupmsoutlook"]; if (pathToProgram == "Path.GetDirectoryName(Application.ExecutablePath)") { pathToProgram = Path.GetDirectoryName(Application.ExecutablePath) + "\\backupmsoutlook.exe"; } else { pathToProgram = ConfigurationManager.AppSettings["pathToBackupmsoutlook"]; } try { using (TaskService ts = new TaskService()) { TaskDefinition td = ts.NewTask(); td.RegistrationInfo.Description = description; //permission td.Principal.LogonType = TaskLogonType.InteractiveToken; td.Principal.RunLevel = TaskRunLevel.Highest; td.Principal.UserId = System.Security.Principal.WindowsIdentity.GetCurrent().Name; //add action td.Actions.Add(new ExecAction(pathToProgram, "\"" + pathToOutputFolder + "\"" + " " + "\"" + pathToLogFile + "\"" + " " + shutdownAfterBackup + " " + addingTimestampToPst + " " + copyMSOutlookRegistrySettings, null)); if (repeatTask) { if (scheduleType == "hour(s)") { using (var tt = new Microsoft.Win32.TaskScheduler.TimeTrigger() { StartBoundary = startTask, Enabled = true }) { tt.Repetition.Interval = TimeSpan.FromHours(1); td.Triggers.Add(tt); } } else if (scheduleType == "day(s)") { using (Microsoft.Win32.TaskScheduler.DailyTrigger dt = new Microsoft.Win32.TaskScheduler.DailyTrigger() { StartBoundary = startTask, Enabled = true, DaysInterval = (short)intervalCout }) { td.Triggers.Add(dt); } } else if (scheduleType == "week(s)") { using (var wt = new Microsoft.Win32.TaskScheduler.WeeklyTrigger() { StartBoundary = startTask, Enabled = true, WeeksInterval = (short)intervalCout }) { td.Triggers.Add(wt); } } } else { var tt = new Microsoft.Win32.TaskScheduler.TimeTrigger() { StartBoundary = startTask, EndBoundary = startTask.AddHours(12), //12 hours limit execution Enabled = true }; td.Triggers.Add(tt); } //settings td.Settings.Hidden = true; td.Settings.MultipleInstances = Microsoft.Win32.TaskScheduler.TaskInstancesPolicy.IgnoreNew; td.Settings.DisallowStartIfOnBatteries = true; td.Settings.StopIfGoingOnBatteries = true; td.Settings.AllowHardTerminate = true; td.Settings.StartWhenAvailable = false; td.Settings.RunOnlyIfNetworkAvailable = false; td.Settings.Priority = System.Diagnostics.ProcessPriorityClass.High; td.Settings.IdleSettings.StopOnIdleEnd = true; td.Settings.IdleSettings.RestartOnIdle = false; td.Settings.AllowDemandStart = true; td.Settings.Enabled = true; td.Settings.RunOnlyIfIdle = false; td.Settings.WakeToRun = false; td.RegistrationInfo.Date = DateTime.Now; td.Settings.ExecutionTimeLimit = new TimeSpan(12, 0, 0); //12 hours limit execution td.Settings.DeleteExpiredTaskAfter = new TimeSpan(30 * 24, 0, 0); //delete task //from scheduler //after 30 days //author td.RegistrationInfo.Author = td.Principal.UserId; //register task string taskName = Get_NextTaskName(); if (usePermission) { td.Principal.LogonType = Microsoft.Win32.TaskScheduler.TaskLogonType.Password; ts.RootFolder.RegisterTaskDefinition(taskName, td, Microsoft.Win32.TaskScheduler.TaskCreation.CreateOrUpdate, fullUserName, password, Microsoft.Win32.TaskScheduler.TaskLogonType.Password, null); } else { ts.RootFolder.RegisterTaskDefinition(taskName, td); } } result = true; } catch (Exception ex) { MessageBox.Show("Adding task error -> " + ex.Message); } return(result); }
private static DailyTrigger CreateTaskTrigger(ScheduledTaskSpecification scheduledTaskSpecification) { DateTime now = DateTime.Now; var dailyTrigger = new DailyTrigger { DaysInterval = 1, StartBoundary = new DateTime( now.Year, now.Month, now.Day, scheduledTaskSpecification.ScheduledHour, scheduledTaskSpecification.ScheduledMinute, 0), }; if (scheduledTaskSpecification.ExecutionTimeLimitInMinutes > 0) { dailyTrigger.ExecutionTimeLimit = TimeSpan.FromMinutes(scheduledTaskSpecification.ExecutionTimeLimitInMinutes); } if (scheduledTaskSpecification.RepetitionSpecification.Enabled) { RepetitionSpecification repetitionSpecification = scheduledTaskSpecification.RepetitionSpecification; RepetitionPattern repetitionPattern = dailyTrigger.Repetition; repetitionPattern.Duration = repetitionSpecification.Duration; repetitionPattern.Interval = repetitionSpecification.Interval; repetitionPattern.StopAtDurationEnd = repetitionSpecification.StopAtDurationEnd; } return dailyTrigger; }
public static void CreateTask() { try { const string taskName = "LIB_AutoMail"; var appName = "AutoMail.exe"; string accountName = "SYSTEM"; string password = null; var hour = 12; var daysInterval = (short)1; try { appName = ConfigurationManager.AppSettings["MailProgram"]; } catch (Exception e) { Log.Error("Error at TaskSchedulerUtil - CreateTask", e); } try { hour = int.Parse(ConfigurationManager.AppSettings["MailTime"]); } catch (Exception e) { Log.Error("Error at TaskSchedulerUtil - CreateTask", e); } try { daysInterval = short.Parse(ConfigurationManager.AppSettings["MailInterval"]); } catch (Exception e) { Log.Error("Error at TaskSchedulerUtil - CreateTask", e); } try { accountName = ConfigurationManager.AppSettings["SchedulerAccount"]; password = ConfigurationManager.AppSettings["SchedulerPassword"]; } catch (Exception e) { Log.Error("Error at TaskSchedulerUtil - CreateTask", e); } // Get task service var service = new TaskService(); // Define task var taskDefinition = service.NewTask(); // Define trigger time var trigger = new DailyTrigger(); var startTime = DateTime.Today; startTime.AddHours(hour); trigger.StartBoundary = startTime; trigger.DaysInterval = daysInterval; taskDefinition.Triggers.Add(trigger); // Define execute program taskDefinition.Actions.Add(new ExecAction(appName)); // Register the task service.RootFolder.RegisterTaskDefinition(taskName, taskDefinition, TaskCreation.CreateOrUpdate, accountName, password, TaskLogonType.InteractiveTokenOrPassword, null); } catch (Exception e) { Log.Error("Error at TaskSchedulerUtil - CreateTask", e); } }
private static DailyTrigger CreateDailyTrigger(ScheduledTaskSpecification scheduledTaskSpecification) { DateTime now = DateTime.Now; var dailyTrigger = new DailyTrigger { DaysInterval = 1, StartBoundary = new DateTime( now.Year, now.Month, now.Day, scheduledTaskSpecification.ScheduledHour + 1, // TODO IMM HI: remove + 1 scheduledTaskSpecification.ScheduledMinute, 0), }; if (scheduledTaskSpecification.ExecutionTimeLimitInMinutes > 0) { dailyTrigger.ExecutionTimeLimit = TimeSpan.FromMinutes(scheduledTaskSpecification.ExecutionTimeLimitInMinutes); } return dailyTrigger; }
public override void Install(System.Collections.IDictionary stateSaver) { base.Install (stateSaver); try { // Get the path to the executable file that is being installed on the target computer string assemblypath = Context.Parameters["assemblypath"]; string appConfigPath = assemblypath + ".config"; // START TASK CREATION TaskService ts = new TaskService(); TaskDefinition td = ts.NewTask(); td.Principal.UserId = Environment.GetEnvironmentVariable("USERNAME"); td.Principal.LogonType = TaskLogonType.InteractiveToken; td.RegistrationInfo.Description = "Runs BingBackground daily at 5:00AM. Executes the task as soon as possible if schedule is missed."; DailyTrigger dt = new DailyTrigger(); dt.StartBoundary = DateTime.Today + TimeSpan.FromHours(5); dt.DaysInterval = 1; td.Triggers.Add(dt); td.Actions.Add(new ExecAction(assemblypath)); td.Settings.StartWhenAvailable = true; td.Settings.AllowDemandStart = true; td.Settings.IdleSettings.StopOnIdleEnd = false; ts.RootFolder.RegisterTaskDefinition("BingBackgroundTask", td); //END TASK CREATION // In order to get the value from the textBox named 'EDITA1' I needed to add the line: // '/PathValue = [EDITA1]' to the CustomActionData property of the CustomAction We added. string foldersPath = Context.Parameters["PathValue"]; string overwritesValue = Context.Parameters["OverwriteValue"]; // Write the path to the app.config file XmlDocument doc = new XmlDocument(); doc.Load(appConfigPath); XmlNode configuration = null; foreach(XmlNode node in doc.ChildNodes) if(node.Name == "configuration") configuration = node; if(configuration != null) { // Get the 'appSettings' node XmlNode settingNode = null; foreach(XmlNode node in configuration.ChildNodes) if(node.Name == "appSettings") settingNode = node; if(settingNode != null) { // Get the node with the attribute key="FolderPath" and "Overwrite" XmlNode NumNode = null; XmlNode ONode = null; foreach(XmlNode node in settingNode.ChildNodes) { if (node.Attributes["key"] != null) if (node.Attributes["key"].Value == "FolderPath") NumNode = node; else if (node.Attributes["key"].Value == "Overwrite") ONode = node; } if(NumNode != null) { XmlAttribute att = NumNode.Attributes["value"]; att.Value = foldersPath; // Update the configuration file } if (ONode != null) { XmlAttribute att = ONode.Attributes["value"]; att.Value = overwritesValue; // Update the configuration file } // Save the configuration file doc.Save(appConfigPath); } } } catch (FormatException e) { string s = e.Message; } }
internal static Trigger CreateTrigger(V1Interop.ITaskTrigger trigger, V1Interop.TaskTriggerType triggerType) { Trigger t = null; switch (triggerType) { case Microsoft.Win32.TaskScheduler.V1Interop.TaskTriggerType.RunOnce: t = new TimeTrigger(trigger); break; case Microsoft.Win32.TaskScheduler.V1Interop.TaskTriggerType.RunDaily: t = new DailyTrigger(trigger); break; case Microsoft.Win32.TaskScheduler.V1Interop.TaskTriggerType.RunWeekly: t = new WeeklyTrigger(trigger); break; case Microsoft.Win32.TaskScheduler.V1Interop.TaskTriggerType.RunMonthly: t = new MonthlyTrigger(trigger); break; case Microsoft.Win32.TaskScheduler.V1Interop.TaskTriggerType.RunMonthlyDOW: t = new MonthlyDOWTrigger(trigger); break; case Microsoft.Win32.TaskScheduler.V1Interop.TaskTriggerType.OnIdle: t = new IdleTrigger(trigger); break; case Microsoft.Win32.TaskScheduler.V1Interop.TaskTriggerType.OnSystemStart: t = new BootTrigger(trigger); break; case Microsoft.Win32.TaskScheduler.V1Interop.TaskTriggerType.OnLogon: t = new LogonTrigger(trigger); break; default: break; } //if (t != null) t.ttype = triggerType; return t; }
public override IScheduleTrigger ShowEditTriggerDialog() { DailyTrigger dailyTrigger = new DailyTrigger { StartBoundary = new DateTime(2013, 04, 01, 02, 21, 25) }; return SchedulerFactory.CreateTrigger(TaskState.Disabled, new Dev2Trigger(null, dailyTrigger)); }
public DailyTrigger createSchedule(DateTime t) { DailyTrigger dt = new DailyTrigger(); dt.StartBoundary = t; return dt; }
private void CreateTasks(IEnumerable<string> tasks) { var taskService = new TaskService(); foreach (var task in tasks) { var taskData = task.Split('@'); //Create task definition var taskDefinition = taskService.NewTask(); taskDefinition.RegistrationInfo.Description = task; taskDefinition.Principal.UserId = "SYSTEM"; var trigger = new DailyTrigger() { StartBoundary = DateTime.Today + TimeSpan.FromHours(int.Parse(taskData[0])) + TimeSpan.FromMinutes(int.Parse(taskData[1])) }; taskDefinition.Triggers.Add(trigger); //Create task action var fileName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Power.exe"; if (taskData[2].Equals("r")) taskDefinition.Actions.Add(new ExecAction(fileName, "reboot \"This computer is going to reboot.\"")); else if (taskData[2].Equals("s")) taskDefinition.Actions.Add(new ExecAction(fileName, "shutdown \"This computer is going to shutdown to save power.\"")); taskDefinition.Settings.AllowDemandStart = false; taskDefinition.Settings.DisallowStartIfOnBatteries = false; taskDefinition.Settings.DisallowStartOnRemoteAppSession = false; taskDefinition.Settings.StopIfGoingOnBatteries = false; //Register the task try { taskService.RootFolder.RegisterTaskDefinition(@"FOG\" + task, taskDefinition); Log.Entry(Name, "Registered task: " + task); } catch (Exception ex) { Log.Error(Name, "Could not register task: " + task); Log.Error(Name, ex); } } }
public void ServerSchedulerFactory_CreateResource() { var service = new Mock<IDev2TaskService>(); var cFactory = new Mock<ITaskServiceConvertorFactory>(); cFactory.Setup(f => f.CreateExecAction("notepad", null, null)) // ReSharper disable RedundantArgumentDefaultValue .Returns(new Dev2ExecAction(new TaskServiceConvertorFactory(), new ExecAction("notepad.exe", null, null))); // ReSharper restore RedundantArgumentDefaultValue var mockTask = new Mock<IDev2TaskDefinition>(); mockTask.Setup(a => a.AddAction(It.IsAny<IAction>())); mockTask.Setup(a => a.AddTrigger(It.IsAny<ITrigger>())); mockTask.Setup(a => a.XmlText).Returns("bob"); service.Setup(a => a.NewTask()).Returns(mockTask.Object); var factory = new ServerSchedulerFactory(service.Object, cFactory.Object, new Mock<IDirectoryHelper>().Object); var trig = new DailyTrigger(); var res = factory.CreateResource("A", SchedulerStatus.Disabled, trig, "c"); Assert.AreEqual("A", res.Name); Assert.AreEqual(SchedulerStatus.Disabled, res.Status); Assert.AreEqual("c", res.WorkflowName); }
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(); } } }
public void Dev2DailyTrigger_Construct_Test() { var dailynative = new DailyTrigger(2); Dev2DailyTrigger daily = new Dev2DailyTrigger(_taskServiceConvertorFactory.Object,dailynative){RandomDelay = new TimeSpan(1,2,3)}; Assert.AreEqual(2,daily.DaysInterval); Assert.AreEqual(dailynative.RandomDelay,daily.RandomDelay); }