/// <summary>Schedule FileWall to start on logon.</summary> private static void ScheduleStartup(string assemblyPath) { //Get a ScheduledTasks object for the local computer. var scheduledTasks = new ScheduledTasks(); scheduledTasks.DeleteTask("FileWall Launch"); // Create a task var task = scheduledTasks.CreateTask("FileWall Launch"); // Fill in the program info task.ApplicationName = assemblyPath; task.Comment = "Launches FileWall when user logs on."; task.Flags |= TaskFlags.RunOnlyIfLoggedOn; // Set the account under which the task should run. task.SetAccountInformation(Environment.ExpandEnvironmentVariables("%USERNAME%"), (string)null); // Create a trigger to start the task every Sunday at 6:30 AM. task.Triggers.Add(new OnLogonTrigger()); // Save the changes that have been made. task.Save(); // Close the task to release its COM resources. task.Close(); // Dispose the ScheduledTasks to release its COM resources. scheduledTasks.Dispose(); }
private static void ScheduleAfterInstall(string assemblyPath) { const string taskName = "FileWall after install launch"; const string taskComment = "Launches FileWall after install."; //Get a ScheduledTasks object for the local computer. var scheduledTasks = new ScheduledTasks(); scheduledTasks.DeleteTask(taskName); // Create a task var task = scheduledTasks.CreateTask(taskName); // Fill in the program info task.ApplicationName = assemblyPath; task.Comment = taskComment; task.Flags |= TaskFlags.RunOnlyIfLoggedOn | TaskFlags.DeleteWhenDone; // Set the account under which the task should run. task.SetAccountInformation(Environment.ExpandEnvironmentVariables("%USERNAME%"), (string)null); // Create a trigger to start the task every Sunday at 6:30 AM. task.Triggers.Add(new RunOnceTrigger(DateTime.Now)); // Save the changes that have been made. task.Save(); task.Run(); // Close the task to release its COM resources. task.Close(); // Dispose the ScheduledTasks to release its COM resources. scheduledTasks.Dispose(); }
public static bool CreateShutDown(ShutDownConfig config) { try { //创建任务计划类 ScheduledTasks st = new ScheduledTasks(); string[] taskNames = st.GetTaskNames(); //删除原有计划 foreach (string name in taskNames) { if (name == "AutoShutDown.job") { st.DeleteTask("AutoShutDown.job"); break; } } //读取路径 string fileDircetoryPath = AppDomain.CurrentDomain.BaseDirectory; StringBuilder shutdownbat = new StringBuilder(); string path = fileDircetoryPath + "gjjh.bat"; //判断是否启用 if (config.IsUsed) { //创建关机批处理 shutdownbat.AppendFormat("at {0}:{1} shutdown -s -t {2}", config.ShutDownHour, config.ShutDownMin, config.ShutDownWaitSec); if (!File.Exists(path)) { FileStream fs = File.Create(path); fs.Close(); } StreamWriter sw = new StreamWriter(path, false, Encoding.GetEncoding("GB2312")); sw.Write(shutdownbat); sw.Flush(); sw.Close(); //创建任务计划 Task task = st.CreateTask("AutoShutDown"); DateTime addTIme = DateTime.Parse(string.Format("{0}:{1}", config.ShutDownHour, config.ShutDownMin)).AddMinutes(-10); DailyTrigger dt = new DailyTrigger(short.Parse(addTIme.Hour.ToString()), short.Parse(addTIme.Minute.ToString())); task.Triggers.Add(dt); task.SetAccountInformation(Environment.UserName, (string)null); task.Flags = TaskFlags.RunOnlyIfLoggedOn | TaskFlags.SystemRequired; task.ApplicationName = fileDircetoryPath + "gjjh.bat"; task.Comment = "触摸屏终端自动关机"; task.Save(); task.Close(); } else if (File.Exists(path)) { //删除批处理 File.Delete(path); } return(true); } catch (Exception ex) { SeatManageComm.WriteLog.Write("添加关机计划失败!" + ex.Message); return(false); } }
private void bREG_Click(object sender, EventArgs e) { ScheduledTasks st = new ScheduledTasks(); st.DeleteTask(TN); Task task = st.CreateTask(TN); task.ApplicationName = Path.Combine(Application.StartupPath, "U4ieServer.exe"); task.Parameters = " \"" + textBox1.Text + "\" \"" + comboBox1.Text + "\" \"" + textBox2.Text + "\" "; task.Triggers.Add(new DailyTrigger(10, 0)); task.Save(); task.DisplayForEdit(); }
private void bREG_Click(object sender, EventArgs e) { E.SetError(tbUri, null); if (tbUri.TextLength == 0) { E.SetError(tbUri, "入力してください"); return; } ScheduledTasks st = new ScheduledTasks(); st.DeleteTask(tbTask.Text); Task task = st.CreateTask(tbTask.Text); task.ApplicationName = System.Reflection.Assembly.GetExecutingAssembly().Location; task.Flags = TaskFlags.SystemRequired; task.MaxRunTime = TimeSpan.FromMinutes(30); task.MaxRunTimeLimited = true; task.Parameters = " \"" + tbUri.Text + "\""; task.WorkingDirectory = Application.StartupPath; if (rbH6.Checked) { DailyTrigger t = new DailyTrigger(9, 0); t.DaysInterval = 1; t.DurationMinutes = 24 * 60; t.IntervalMinutes = 6 * 60; task.Triggers.Add(t); } else if (rbD1.Checked) { DailyTrigger t = new DailyTrigger(9, 0); t.DaysInterval = 1; task.Triggers.Add(t); } else if (rbD3.Checked) { DailyTrigger t = new DailyTrigger(9, 0); t.DaysInterval = 3; task.Triggers.Add(t); } task.Save(tbTask.Text); task.DisplayForEdit(); }
public static void ScheduleTask(string name, string appname, string parameters) { Task t = Exists(name) ? tasks.OpenTask(name) : tasks.CreateTask(name); try { t.ApplicationName = appname; t.Parameters = parameters; t.Save(); if (t.DisplayPropertySheet()) { t.Save(); } } finally { t.Close(); } }
private bool IniciarWindows() { string nombreApp = (Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)).Replace("Config.exe", ""); ScheduledTasks Tareas = new ScheduledTasks(); string[] Existen = Tareas.GetTaskNames(); short hora = Convert.ToInt16(TimePicker.Text.Substring(0, 2)); short min = Convert.ToInt16(TimePicker.Text.Substring(3, 2)); string pass = null; if (chkInicioW.Checked == true) { try { //Referencia https://www.codeproject.com/Articles/2407/A-New-Task-Scheduler-Class-Library-for-NET if (!Existen.Contains(nombreApp + ".job")) { TaskScheduler.Task tarea = Tareas.CreateTask(nombreApp); tarea.ApplicationName = txtRutaRead.Text; tarea.Comment = "Tarea para ejecutar el ReadFiles diariamente"; tarea.SetAccountInformation(Environment.UserName, pass); tarea.Creator = Environment.UserName; tarea.Priority = System.Diagnostics.ProcessPriorityClass.Normal; tarea.Triggers.Add(new DailyTrigger(hora, min)); tarea.Flags = TaskFlags.RunOnlyIfLoggedOn; tarea.Save(); tarea.Close(); } else if (chkEdit.Checked) { TaskScheduler.Task tarea = Tareas.OpenTask(nombreApp); tarea.Triggers.RemoveAt(0); tarea.Triggers.Add(new DailyTrigger(hora, min)); tarea.Save(); tarea.Close(); } Tareas.Dispose(); Prox_Ejec(); txtPassWind.Text = ""; return(true); } catch (Exception e) { Tareas.DeleteTask(nombreApp); Tareas.Dispose(); MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Prox_Ejec(); return(false); } } else { try { Tareas.DeleteTask(nombreApp); Tareas.Dispose(); Prox_Ejec(); return(true); } catch (Exception e) { Prox_Ejec(); return(false); } } }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); UserAccount Account = new UserAccount(); // We can'task set up a scheduled task if the user has no password, so test this first: if (Account.IsUserPasswordBlank()) { MessageBox.Show(Properties.Resources.ErrorBlankPassword, Properties.Resources.MsgTitle, MessageBoxButtons.OK, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification); return; } // Ensure the Task Scheduler service is running: ServiceController sc = new ServiceController("Schedule"); try { if (sc.Status == ServiceControllerStatus.Stopped) { const int SixtySecondsAsMilliSeconds = 60 * 1000; TimeSpan timeout = TimeSpan.FromMilliseconds(SixtySecondsAsMilliSeconds); sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running, timeout); } } catch { MessageBox.Show(Properties.Resources.ErrorSchedulerService, Properties.Resources.MsgTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } // Initiate link to Windows Task Scheduler: const string TaskNameRoot = "SIL FieldWorks Backup"; const string TaskNameExtRoot = TaskNameRoot + " by "; string TaskName = TaskNameExtRoot + Account.AccountNameAlt; // Investigate if there are any backup schedules created by others: ScheduledTasks TaskList = new ScheduledTasks(); string[] TaskNames = TaskList.GetTaskNames(); string ScheduleOwners = ""; bool fMeIncluded = false; int ctOtherUsersSchedules = 0; foreach (string CurrentTaskName in TaskNames) { if (CurrentTaskName.StartsWith(TaskNameExtRoot)) { string Schedule = ""; Task CurrentTask = TaskList.OpenTask(CurrentTaskName); if (CurrentTask != null) { foreach (Trigger tr in CurrentTask.Triggers) { if (Schedule.Length > 0) { Schedule += "; "; } Schedule += tr.ToString(); } CurrentTask.Close(); } string Owner = CurrentTaskName.Substring(TaskNameExtRoot.Length); if (Owner.EndsWith(".job", StringComparison.CurrentCultureIgnoreCase)) { Owner = Owner.Remove(Owner.Length - 4); } if (Owner == Account.AccountNameAlt) { fMeIncluded = true; ScheduleOwners += Properties.Resources.MsgOtherSchedulersMe; } else { ScheduleOwners += Owner; ctOtherUsersSchedules++; } ScheduleOwners += ": " + ((Schedule.Length > 0) ? Schedule : Properties.Resources.MsgScheduleNotAccessible); ScheduleOwners += Environment.NewLine; } } if (ctOtherUsersSchedules > 0) { string Msg = Properties.Resources.MsgOtherSchedulers + Environment.NewLine + ScheduleOwners + Environment.NewLine + (fMeIncluded? Properties.Resources.MsgOtherSchedulersAndMe : Properties.Resources.MsgOtherSchedulersNotMe) + Environment.NewLine + Properties.Resources.MsgOtherSchedulersAddendum; if (MessageBox.Show(Msg, Properties.Resources.MsgTitle, MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == DialogResult.Cancel) { return; } } // Retrieve the current Backup task, if there is one: bool fPreExistingTask = true; Task task = TaskList.OpenTask(TaskName); // If there isn'task one already, make a new one: if (task == null) { fPreExistingTask = false; task = TaskList.CreateTask(TaskName); if (task == null) { MessageBox.Show(Properties.Resources.ErrorNoTask, Properties.Resources.ErrorMsgTitle, MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } // Set the program to run on the schedule by looking up the FW location: string ScriptPath = null; RegistryKey rKey = Registry.LocalMachine.OpenSubKey(FwHive); if (rKey != null) { System.Object regObj = rKey.GetValue(FwCodeDir); if (regObj != null) { string FwFolder = regObj.ToString(); if (!FwFolder.EndsWith(@"\")) { FwFolder += @"\"; } ScriptPath = FwFolder + FwBackupScript; } } if (ScriptPath == null) { MessageBox.Show(Properties.Resources.ErrorNoScript, Properties.Resources.ErrorMsgTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // On 64-bit machines, we have to force the scheduled script to run with the 32-bit // version of the script engine, otherwise it fails to load the 32-bit COM class // in the script: if (Is64Bit()) { // Create the path to the 32-bit script engine: task.ApplicationName = Environment.GetEnvironmentVariable("WINDIR") + @"\SysWOW64\wscript.exe"; // put the path to the script in as the parameter to the script engine: task.Parameters = "\"" + ScriptPath + "\""; } else { task.ApplicationName = ScriptPath; task.Parameters = ""; } task.Comment = "Created automatically by FieldWorks Backup system."; // Give it an arbitrary weekday run at 5 in the afternoon: task.Triggers.Add(new WeeklyTrigger(17, 0, DaysOfTheWeek.Monday | DaysOfTheWeek.Tuesday | DaysOfTheWeek.Wednesday | DaysOfTheWeek.Thursday | DaysOfTheWeek.Friday)); } // Display the Windows Task Scheduler schedule page for our task: bool fDisplaySchedule = true; while (fDisplaySchedule) { if (task.DisplayPropertySheet(Task.PropPages.Schedule)) { // User pressed OK on Schedule page. DialogResult DlgResult; bool fPasswordCorrect = false; do { // User must give their Windows logon password in order to use schedule: BackupSchedulePasswordDlg PwdDlg = new BackupSchedulePasswordDlg(); DlgResult = PwdDlg.ShowDialog(); SecureString Password = PwdDlg.Password; PwdDlg.Dispose(); if (DlgResult == DialogResult.OK) { try { // Test if the password the user gave is correct: fPasswordCorrect = Account.IsPasswordCorrect(Password); if (fPasswordCorrect) { // Configure the scheduled task with the user account details: task.SetAccountInformation(Account.AccountName, Password); task.Save(); fDisplaySchedule = false; } } catch (System.Exception e) { if (e.Message == "Password error") { DlgResult = DialogResult.Cancel; } } } } while (DlgResult == DialogResult.OK && !fPasswordCorrect); } else // User pressed cancel on Task Scheduler dialog { if (fPreExistingTask) { // Give user the option to delete the pre-existing shceduled backup. // Make a string listing the scheduled backup time(s): string Schedule = Properties.Resources.MsgCurrentSchedule; Schedule += Environment.NewLine; foreach (Trigger tr in task.Triggers) { Schedule += tr.ToString() + Environment.NewLine; } Schedule += Environment.NewLine; if (MessageBox.Show( Schedule + Properties.Resources.MsgDeleteExistingTask, Properties.Resources.MsgTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes) { task.Close(); task = null; TaskList.DeleteTask(TaskName); } } fDisplaySchedule = false; } } // End while fDisplaySchedule if (task != null) { task.Close(); } }
//Đồng Ý private void btnOK_Click(object sender, EventArgs e) { try { if ((getNameScheduled() != "") && (getTimeStart() != "")) { if (MessageBox.Show("Bạn Có Chắc Chắn Muốn Thêm Một Lịch Trình Mới Không", "Time Manager", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { string strTimeStart = getTimeStart(); st = new ScheduledTasks(global.getNameComputer()); try { st.DeleteTask(frmTimeManager.strNameScheduled); } catch { } t = st.CreateTask(getNameScheduled()); if (txtNameApplication.Text != "") { t.ApplicationName = getNameApplication(); t.SetAccountInformation(frmSetAccount.strUserName, frmSetAccount.strPassWord); } t.Flags = TaskFlags.SystemRequired; short shortHourStart = Convert.ToInt16(global.getHour(getTimeStart())); #region Hàng Ngày //Hàng Ngày if (cbLichTrinh.Text == "Hằng Ngày") { if (global.getPeriod(strTimeStart) == "PM") { shortHourStart = Convert.ToInt16(shortHourStart + 12); } t.Triggers.Add(new DailyTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), Convert.ToInt16(dtpDaily.Text))); t.Save(); st.Dispose(); t.Dispose(); } #endregion #region Hàng Tuần //Hàng Tuần if (cbLichTrinh.Text == "Hằng Tuần") { if (cbMondayWeekly.Checked) { t.Triggers.Add(new WeeklyTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), DaysOfTheWeek.Monday)); } if (cbTuesdayWeekly.Checked) { t.Triggers.Add(new WeeklyTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), DaysOfTheWeek.Tuesday)); } if (cbWednesdayWeekly.Checked) { t.Triggers.Add(new WeeklyTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), DaysOfTheWeek.Wednesday)); } if (cbThursdayWeekly.Checked) { t.Triggers.Add(new WeeklyTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), DaysOfTheWeek.Thursday)); } if (cbFridayWeekly.Checked) { t.Triggers.Add(new WeeklyTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), DaysOfTheWeek.Friday)); } if (cbSaturdayWeekly.Checked) { t.Triggers.Add(new WeeklyTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), DaysOfTheWeek.Saturday)); } if (cbSundayWeekly.Checked) { t.Triggers.Add(new WeeklyTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), DaysOfTheWeek.Sunday)); } if (!(cbMondayWeekly.Checked) && !(cbTuesdayWeekly.Checked) && !(cbWednesdayWeekly.Checked) && !(cbThursdayWeekly.Checked) && !(cbFridayWeekly.Checked) && !(cbSaturdayWeekly.Checked) && !(cbSundayWeekly.Checked)) { MessageBox.Show("Bạn Chưa Chọn Bất Kỳ Ngày Nào Trong Tuần", "Time Manager", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { t.Save(); } } #endregion #region Hàng Tháng if (cbLichTrinh.Text == "Hằng Tháng") { if (cbNgayThuMonthly.Checked) { int[] intArray = { Convert.ToInt32(dtpMonthly.Text.Trim()) }; if (frmSelectMonth.boolCheck1) { t.Triggers.Add(new MonthlyTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), intArray, MonthsOfTheYear.January)); } if (frmSelectMonth.boolCheck2) { t.Triggers.Add(new MonthlyTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), intArray, MonthsOfTheYear.February)); } if (frmSelectMonth.boolCheck3) { t.Triggers.Add(new MonthlyTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), intArray, MonthsOfTheYear.March)); } if (frmSelectMonth.boolCheck4) { t.Triggers.Add(new MonthlyTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), intArray, MonthsOfTheYear.April)); } if (frmSelectMonth.boolCheck5) { t.Triggers.Add(new MonthlyTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), intArray, MonthsOfTheYear.May)); } if (frmSelectMonth.boolCheck6) { t.Triggers.Add(new MonthlyTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), intArray, MonthsOfTheYear.June)); } if (frmSelectMonth.boolCheck7) { t.Triggers.Add(new MonthlyTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), intArray, MonthsOfTheYear.July)); } if (frmSelectMonth.boolCheck8) { t.Triggers.Add(new MonthlyTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), intArray, MonthsOfTheYear.August)); } if (frmSelectMonth.boolCheck9) { t.Triggers.Add(new MonthlyTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), intArray, MonthsOfTheYear.September)); } if (frmSelectMonth.boolCheck10) { t.Triggers.Add(new MonthlyTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), intArray, MonthsOfTheYear.October)); } if (frmSelectMonth.boolCheck11) { t.Triggers.Add(new MonthlyTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), intArray, MonthsOfTheYear.November)); } if (frmSelectMonth.boolCheck12) { t.Triggers.Add(new MonthlyTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), intArray, MonthsOfTheYear.December)); } t.Save(); } if (cbCuaThangMonthly.Checked) { if (frmSelectMonth.boolCheck1) { t.Triggers.Add(new TaskScheduler.MonthlyDOWTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), getDaysOfTheWeek_Monthly(), getWhichWeek_Monthly(), MonthsOfTheYear.January)); } if (frmSelectMonth.boolCheck2) { t.Triggers.Add(new TaskScheduler.MonthlyDOWTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), getDaysOfTheWeek_Monthly(), getWhichWeek_Monthly(), MonthsOfTheYear.February)); } if (frmSelectMonth.boolCheck3) { t.Triggers.Add(new TaskScheduler.MonthlyDOWTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), getDaysOfTheWeek_Monthly(), getWhichWeek_Monthly(), MonthsOfTheYear.March)); } if (frmSelectMonth.boolCheck4) { t.Triggers.Add(new TaskScheduler.MonthlyDOWTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), getDaysOfTheWeek_Monthly(), getWhichWeek_Monthly(), MonthsOfTheYear.April)); } if (frmSelectMonth.boolCheck5) { t.Triggers.Add(new TaskScheduler.MonthlyDOWTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), getDaysOfTheWeek_Monthly(), getWhichWeek_Monthly(), MonthsOfTheYear.May)); } if (frmSelectMonth.boolCheck6) { t.Triggers.Add(new TaskScheduler.MonthlyDOWTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), getDaysOfTheWeek_Monthly(), getWhichWeek_Monthly(), MonthsOfTheYear.June)); } if (frmSelectMonth.boolCheck7) { t.Triggers.Add(new TaskScheduler.MonthlyDOWTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), getDaysOfTheWeek_Monthly(), getWhichWeek_Monthly(), MonthsOfTheYear.November)); } if (frmSelectMonth.boolCheck8) { t.Triggers.Add(new TaskScheduler.MonthlyDOWTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), getDaysOfTheWeek_Monthly(), getWhichWeek_Monthly(), MonthsOfTheYear.December)); } if (frmSelectMonth.boolCheck9) { t.Triggers.Add(new TaskScheduler.MonthlyDOWTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), getDaysOfTheWeek_Monthly(), getWhichWeek_Monthly(), MonthsOfTheYear.September)); } if (frmSelectMonth.boolCheck10) { t.Triggers.Add(new TaskScheduler.MonthlyDOWTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), getDaysOfTheWeek_Monthly(), getWhichWeek_Monthly(), MonthsOfTheYear.October)); } if (frmSelectMonth.boolCheck11) { t.Triggers.Add(new TaskScheduler.MonthlyDOWTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), getDaysOfTheWeek_Monthly(), getWhichWeek_Monthly(), MonthsOfTheYear.May)); } if (frmSelectMonth.boolCheck12) { t.Triggers.Add(new TaskScheduler.MonthlyDOWTrigger(shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), getDaysOfTheWeek_Monthly(), getWhichWeek_Monthly(), MonthsOfTheYear.June)); } t.Save(); } } #endregion #region Một Lần if (cbLichTrinh.Text == "Một Lần") { int intGetDay = Convert.ToInt32(global.getDay(dtpOnce.Text.Trim())); int intGetMonth = Convert.ToInt32(global.getMonth(dtpOnce.Text.Trim())); int intGetYear = Convert.ToInt32(global.getYear(dtpOnce.Text.Trim())); t.Triggers.Add(new TaskScheduler.RunOnceTrigger(new DateTime(intGetYear, intGetMonth, intGetDay, shortHourStart, Convert.ToInt16(global.getMinute(getTimeStart())), 0))); t.Save(); } #endregion #region Lúc Hệ Thống Bắt Đầu + Logon + Không Làm Việc if (cbLichTrinh.Text == "Lúc Bằt Đầu Hệ Thống") { t.Triggers.Add(new TaskScheduler.OnSystemStartTrigger()); t.Save(); } if (cbLichTrinh.Text == "Lúc Log On") { t.Triggers.Add(new TaskScheduler.OnLogonTrigger()); t.Save(); } if (cbLichTrinh.Text == "Khi Không Làm Việc") { t.Triggers.Add(new TaskScheduler.OnIdleTrigger()); //SetScreenSaverTimeout(Convert.ToInt32(txtIdle.Text.Trim()) * 60); t.Save(); } #endregion //t.Save(); this.Close(); } } else { MessageBox.Show("Bạn Chưa Chọn Tên Công Việc Hoặc Giờ Bắt Đầu", "Time Manager", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Time Manager", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private async void btnCreate_Click(object sender, RoutedEventArgs e) { List <Guid> opIds; List <OperationStatus> opStatus; var tasks = new TaskModel[5]; tasks = GetTasks(); //Synchronous creation of tasks txtStatus.Text += "Starting synchronous task creation."; //start creating tasks and get the list of operation Ids opIds = new List <Guid>(); opStatus = new List <OperationStatus>(); foreach (TaskModel t in tasks) { try { opIds.Add(scheduledTask.CreateTask(t)); } catch (SchedulerModelValidationException me) { txtStatus.Text += "\n" + me.ExceptionMessage; //TODO: Log exception } catch (SchedulerException schedExp) { //TODO: Log exception } } txtStatus.Text += "\nGot operationIds, now checking status"; //get operation status for each operationId if (opIds.Count > 0) { try { opStatus = opIds.Select(t => scheduledTask.GetOperationStatus(t, true)).ToList(); } catch (SchedulerException shedExp) { //TODO: Log exception } if (opStatus.Count > 0) { DisplayOperationStatus(opStatus); } } txtStatus.Text += "\nEnding synchronous task creation."; //Asynsynchronous creation of tasks txtStatus.Text += "\nStarting asynsynchronous task creation."; //opIds = await CreatTasksAsync(); foreach (TaskModel t in tasks) { try { var currentOperationId = await scheduledTask.CreateTaskAsync(t); opIds.Add(currentOperationId); } catch (SchedulerModelValidationException me) { //write to log txtStatus.Text += "\n" + me.ExceptionMessage; } catch (SchedulerException exp) { //write to log } } txtStatus.Text += "\nGot operationIds, now checking status"; if (opIds.Count > 0) { foreach (Guid t in opIds) { try { var currentStatus = await scheduledTask.GetOperationStatusAsync(t, true); opStatus.Add(currentStatus); } catch (SchedulerException exp) { //write log } } if (opStatus.Count > 0) { DisplayOperationStatus(opStatus); } } txtStatus.Text += "\nEnding asyncsynchronous task creation."; }
/// <summary> /// Add new task or update existing /// </summary> /// <param name="?"></param> public static void AddTask(ref ClamWinScheduleData data) { lock (MainLock) { Task task; try { // Delete previous task if exists tasks.DeleteTask(data.TaskName); // Create new task = tasks.CreateTask(data.TaskName); } catch (ArgumentException) { return; } task.ApplicationName = ClamWinPathName; task.Parameters = "-" + data.CmdLineArguments; task.Comment = "ClamWin " + data.Name + "."; task.IdleWaitMinutes = 0; task.Priority = System.Diagnostics.ProcessPriorityClass.Normal; switch (data.Type) { case ClamWinScheduleData.SchedulingTypes.Once: { task.Triggers.Add(new RunOnceTrigger(data.Date)); break; } case ClamWinScheduleData.SchedulingTypes.Minutely: { DateTime date = DateTime.Now; date = date.Add(new TimeSpan(0, data.Frequency, 0)); Trigger trigger = new DailyTrigger((short)date.Hour, (short)date.Minute, 1); trigger.DurationMinutes = 24 * 60; trigger.IntervalMinutes = data.Frequency; task.Triggers.Add(trigger); //TODO: no such trigger available currently break; } case ClamWinScheduleData.SchedulingTypes.Hourly: { DateTime date = DateTime.Now; date = date.Add(new TimeSpan(data.Frequency, 0, 0)); Trigger trigger = new DailyTrigger((short)date.Hour, (short)date.Minute, 1); trigger.DurationMinutes = 24 * 60; trigger.IntervalMinutes = data.Frequency * 60; task.Triggers.Add(trigger); //TODO: no such trigger available currently break; } case ClamWinScheduleData.SchedulingTypes.Daily: { short hour = 0; short minutes = 0; if (data.UseDateTime) { hour = (short)data.Date.Hour; minutes = (short)data.Date.Minute; } switch (data.DailyType) { case ClamWinScheduleData.DailyTypes.EveryNDays: { task.Triggers.Add(new DailyTrigger(hour, minutes, (short)data.Frequency)); break; } case ClamWinScheduleData.DailyTypes.EveryWeekday: { task.Triggers.Add(new DailyTrigger(hour, minutes)); break; } case ClamWinScheduleData.DailyTypes.EveryWeekend: { task.Triggers.Add(new WeeklyTrigger(hour, minutes, DaysOfTheWeek.Saturday | DaysOfTheWeek.Sunday)); break; } } break; } case ClamWinScheduleData.SchedulingTypes.Weekly: { short hour = 0; short minutes = 0; if (data.UseDateTime) { hour = (short)data.Date.Hour; minutes = (short)data.Date.Minute; } task.Triggers.Add(new WeeklyTrigger(hour, minutes, (DaysOfTheWeek)data.Days)); break; } case ClamWinScheduleData.SchedulingTypes.Monthly: { short hour = 0; short minutes = 0; if (data.UseDateTime) { hour = (short)data.Date.Hour; minutes = (short)data.Date.Minute; } int[] day = new int[1]; day[0] = data.Frequency; task.Triggers.Add(new MonthlyTrigger(hour, minutes, day)); break; } } task.Save(); task.Close(); } }