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 string AddMonthlyTrigger(DateTime startTime) { MonthlyTrigger mt = new MonthlyTrigger(); mt.StartBoundary = startTime; taskDef.Triggers.Add(mt); triggers.Add(mt); task.RootFolder.RegisterTaskDefinition(this.taskName, taskDef, TaskCreation.CreateOrUpdate, null, null, TaskLogonType.InteractiveToken, null); return "Added"; }
public void TestMonthlySelect() { var span1 = new MonthlyTrigger(2, MonthsOfTheYear.February) { 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.Month == 2); Debug.Assert(r[0].TimeOfDay == new TimeSpan(18, 0, 0)); Debug.Assert(r[1].Date == r[0].Date.AddYears(1)); Debug.Assert(r[1].TimeOfDay == new TimeSpan(18, 0, 0)); Debug.Assert(r[2].Date == r[1].Date.AddYears(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.Month == 2); 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.AddYears(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).AddYears(1).AddHours(19); // move back to a januaray, then advance r = span1.SelectDates(x => x).Take(6).ToArray(); Debug.Assert(r.Length == 5); Debug.Assert(r[0].Date.Month == 2); 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.AddYears(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; for (var i = 0; i < 2; i++) { r = span1.SelectDates(x => x, DateTime.Today.AddDays(i * 7)).Take(5).ToArray(); Debug.Assert(r.Length == 5); Debug.Assert(r[0].Date.DayOfWeek == DayOfWeek.Tuesday); 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(14)); 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)); } }
/// <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 Dev2MonthlyTrigger(ITaskServiceConvertorFactory taskServiceConvertorFactory, MonthlyTrigger instance) : base(taskServiceConvertorFactory, instance) { }
private void monthlyTriggerUI1_TriggerTypeChanged(object sender, EventArgs e) { if (!onAssignment) { Trigger newTrigger = null; if (monthlyTriggerUI1.TriggerType == TaskTriggerType.Monthly) newTrigger = new MonthlyTrigger(); else newTrigger = new MonthlyDOWTrigger(); if (newTrigger != null) { if (trigger != null) newTrigger.CopyProperties(trigger); this.Trigger = newTrigger; } } }
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; }
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ń!"); }
public void Dev2MonthlyTrigger_Construct_Test() { var native = new MonthlyTrigger(2,MonthsOfTheYear.April); var wrapped = new Dev2MonthlyTrigger(_taskServiceConvertorFactory.Object, native); Assert.AreEqual(native, wrapped.Instance); Assert.AreEqual(native.DaysOfMonth[0], wrapped.DaysOfMonth[0]); Assert.AreEqual(native.MonthsOfYear,wrapped.MonthsOfYear); Assert.AreEqual(native.RandomDelay,wrapped.RandomDelay); Assert.AreEqual(native.RunOnLastDayOfMonth,wrapped.RunOnLastDayOfMonth); }
//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"; } }
/// <summary> /// Creates a trigger using a cron string. /// </summary> /// <param name="cronString">String using cron defined syntax for specifying a time interval. See remarks for syntax.</param> /// <returns>Array of <see cref="Trigger" /> representing the specified cron string.</returns> /// <exception cref="System.NotImplementedException">Unsupported cron string.</exception> /// <remarks> /// <para>NOTE: This method does not support all combinations of cron strings. Please test extensively before use. Please post an issue with any syntax that should work, but doesn't.</para> /// <para>Currently the cronString only supports numbers and not any of the weekday or month strings. Please use numeric equivalent.</para> /// <para>This section borrows liberally from the site http://www.nncron.ru/help/EN/working/cron-format.htm. The cron format consists of five fields separated by white spaces:</para> /// <code> /// <Minute> <Hour> <Day_of_the_Month> <Month_of_the_Year> <Day_of_the_Week> /// </code> /// <para>Each item has bounds as defined by the following:</para> /// <code> /// * * * * * /// | | | | | /// | | | | +---- Day of the Week (range: 1-7, 1 standing for Monday) /// | | | +------ Month of the Year (range: 1-12) /// | | +-------- Day of the Month (range: 1-31) /// | +---------- Hour (range: 0-23) /// +------------ Minute (range: 0-59) /// </code> /// <para>Any of these 5 fields may be an asterisk (*). This would mean the entire range of possible values, i.e. each minute, each hour, etc.</para> /// <para>Any of the first 4 fields can be a question mark ("?"). It stands for the current time, i.e. when a field is processed, the current time will be substituted for the question mark: minutes for Minute field, hour for Hour field, day of the month for Day of month field and month for Month field.</para> /// <para>Any field may contain a list of values separated by commas, (e.g. 1,3,7) or a range of values (two integers separated by a hyphen, e.g. 1-5).</para> /// <para>After an asterisk (*) or a range of values, you can use character / to specify that values are repeated over and over with a certain interval between them. For example, you can write "0-23/2" in Hour field to specify that some action should be performed every two hours (it will have the same effect as "0,2,4,6,8,10,12,14,16,18,20,22"); value "*/4" in Minute field means that the action should be performed every 4 minutes, "1-30/3" means the same as "1,4,7,10,13,16,19,22,25,28".</para> /// </remarks> public static Trigger[] FromCronFormat(string cronString) { CronExpression cron = new CronExpression(); cron.Parse(cronString); // TODO: Figure out all the permutations of expression and convert to Trigger(s) /* Time (fields 1-4 have single number and dow = *) * Time repeating * Daily * Weekly * Monthly * Monthly DOW */ List<Trigger> ret = new List<Trigger>(); // MonthlyDOWTrigger if (!cron.DOW.IsEvery) { // Determine DOW DaysOfTheWeek dow = 0; if (cron.DOW.vals.Length == 0) dow = DaysOfTheWeek.AllDays; else if (cron.DOW.range) for (int i = cron.DOW.vals[0]; i <= cron.DOW.vals[1]; i += cron.DOW.step) dow |= (DaysOfTheWeek)(1 << (i - 1)); else for (int i = 0; i < cron.DOW.vals.Length; i++) dow |= (DaysOfTheWeek)(1 << (cron.DOW.vals[i] - 1)); // Determine months MonthsOfTheYear moy = 0; if ((cron.Months.vals.Length == 0 || (cron.Months.vals.Length == 1 && cron.Months.vals[0] == 1)) && cron.Months.IsEvery) moy = MonthsOfTheYear.AllMonths; else if (cron.Months.range) for (int i = cron.Months.vals[0]; i <= cron.Months.vals[1]; i += cron.Months.step) moy |= (MonthsOfTheYear)(1 << (i - 1)); else for (int i = 0; i < cron.Months.vals.Length; i++) moy |= (MonthsOfTheYear)(1 << (cron.Months.vals[i] - 1)); Trigger tr = new MonthlyDOWTrigger(dow, moy, WhichWeek.AllWeeks); ret.AddRange(ProcessCronTimes(cron, tr)); } // MonthlyTrigger else if (cron.Days.vals.Length > 0) { // Determine DOW List<int> days = new List<int>(); if (cron.Days.range) for (int i = cron.Days.vals[0]; i <= cron.Days.vals[1]; i += cron.Days.step) days.Add(i); else for (int i = 0; i < cron.Days.vals.Length; i++) days.Add(cron.Days.vals[i]); // Determine months MonthsOfTheYear moy = 0; if ((cron.Months.vals.Length == 0 || (cron.Months.vals.Length == 1 && cron.Months.vals[0] == 1)) && cron.Months.IsEvery) moy = MonthsOfTheYear.AllMonths; else if (cron.Months.range) for (int i = cron.Months.vals[0]; i <= cron.Months.vals[1]; i += cron.Months.step) moy |= (MonthsOfTheYear)(1 << (i - 1)); else for (int i = 0; i < cron.Months.vals.Length; i++) moy |= (MonthsOfTheYear)(1 << (cron.Months.vals[i] - 1)); Trigger tr = new MonthlyTrigger(1, moy) { DaysOfMonth = days.ToArray() }; ret.AddRange(ProcessCronTimes(cron, tr)); } // DailyTrigger else if (cron.Months.IsEvery && cron.DOW.IsEvery && cron.Days.repeating) { Trigger tr = new DailyTrigger((short)cron.Days.step); ret.AddRange(ProcessCronTimes(cron, tr)); } else { throw new NotImplementedException(); } return ret.ToArray(); }