public static bool GetShotDownSetting(ref ShutDownConfig config) { try { //创建任务计划类 ScheduledTasks st = new ScheduledTasks(); string[] taskNames = st.GetTaskNames(); config.IsUsed = false; foreach (string name in taskNames) { if (name == "AutoShutDown.job") { config.IsUsed = true; break; } } string fileDircetoryPath = AppDomain.CurrentDomain.BaseDirectory; StringBuilder shutdownbat = new StringBuilder(); string path = fileDircetoryPath + "gjjh.bat"; if (File.Exists(path)) { StreamReader sr = new StreamReader(path); string str = sr.ReadLine(); sr.Close(); config.ShutDownHour = str.Substring(3, str.IndexOf(':') - 3); config.ShutDownMin = str.Substring(str.IndexOf(':') + 1, 2).Trim(); config.ShutDownWaitSec = str.Substring(str.LastIndexOf(' ') + 1); } return(true); } catch (Exception ex) { SeatManageComm.WriteLog.Write("获取关机计划失败!" + ex.Message); return(false); } }
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); } }
public static bool Exists(string name) { string[] names = tasks.GetTaskNames(); foreach (string tested in names) { if (Path.GetFileNameWithoutExtension(tested).ToLower() == name.ToLower()) { return(true); } } return(false); }
private void toolStripButton5_Click(object sender, EventArgs e) { if (MessageBox.Show("Bạn Có Chắc Chắn Muốn Xoá Toàn Bộ Công Việc", "Time Manager", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { ScheduledTasks st = new ScheduledTasks(global.getNameComputer()); string[] taskNames = st.GetTaskNames(); foreach (string name in taskNames) { st.DeleteTask(name); } LoadDataOnListView(); } }
public void LoadDataOnListView() { lswTimeManager.Items.Clear(); ScheduledTasks st = new ScheduledTasks(global.getNameComputer()); string[] taskNames = st.GetTaskNames(); Task t; int i = 0; foreach (string name in taskNames) { t = st.OpenTask(name); lswTimeManager.Items.Add(name); lswTimeManager.Items[i].SubItems.Add(name); lswTimeManager.Items[i].SubItems.Add(t.NextRunTime.ToString()); i++; //Lần Chạy Kế Tiếp //MessageBox.Show(global.getMonth(t.NextRunTime.ToShortDateString())); // MessageBox.Show(t.Status.ToString()); } }
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(); } }