/// <summary> /// Изменить состояние задачи в Windows Task Scheduler. /// </summary> /// <param name="taskName"> название задачи </param> /// <param name="isStart"> запустить, если true, остановить, если false </param> /// <returns> результат выполнения </returns> public static ActionResult ChangeTaskState(string taskName, bool isStart) { string msg = ""; bool isSuccessful = false; try { ITaskService ts = new TaskSchedulerClass(); ts.Connect("localhost"); ITaskFolder taskFolder = ts.GetFolder("\\"); IRegisteredTask task = taskFolder.GetTask(taskName); if (isStart) { task.Run(null); } else { task.Stop(0); task.Enabled = false; } isSuccessful = true; } catch (Exception e) { msg = e.Message; } return(new ActionResult(isSuccessful, msg)); }
private void deleteTask(string reportid) { DataTableReader dtrSch = DataBase.dbDataTable("Select * from ReportSchedule where ID=" + reportid).CreateDataReader(); if (dtrSch.HasRows) { dtrSch.Read(); string ReportName = dtrSch["ReportName"].ToString().Trim(); string ReportDBID = dtrSch["ReportID"].ToString().Trim(); ITaskService taskService = new TaskSchedulerClass(); taskService.Connect(); ITaskFolder containingFolder = taskService.GetFolder(@"\SSADL"); containingFolder.DeleteTask(ReportName, 0); string path = commonfunctions.BaseDirectory + "/batFiles/report_" + ReportDBID + ".bat"; // Delete the file if it exists. if (File.Exists(path)) { File.Delete(path); } } }
private void CreateSchedulerTask() { ITaskDefinition definition = scheduler.NewTask(0); definition.RegistrationInfo.Description = "This task starts the Open Hardware Monitor on Windows startup."; definition.Principal.RunLevel = TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST; definition.Settings.DisallowStartIfOnBatteries = false; definition.Settings.StopIfGoingOnBatteries = false; definition.Settings.ExecutionTimeLimit = "PT0S"; ILogonTrigger trigger = (ILogonTrigger)definition.Triggers.Create( TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON); IExecAction action = (IExecAction)definition.Actions.Create( TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Path = Application.ExecutablePath; action.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath); ITaskFolder root = scheduler.GetFolder("\\"); ITaskFolder folder; try { folder = root.GetFolder("Open Hardware Monitor"); } catch (IOException) { folder = root.CreateFolder("Open Hardware Monitor", ""); } folder.RegisterTaskDefinition("Startup", definition, (int)TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null, TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, ""); }
public StartupManager() { try { scheduler = new TaskSchedulerClass(); scheduler.Connect(null, null, null, null); } catch (Exception) { scheduler = null; } if (scheduler != null) { try { ITaskFolder folder = scheduler.GetFolder("\\Open Hardware Monitor"); IRegisteredTask task = folder.GetTask("Startup"); startup = task != null; } catch (FileNotFoundException) { startup = false; } } else { RegistryKey key = Registry.CurrentUser.OpenSubKey(REGISTRY_RUN); startup = false; if (key != null) { string value = (string)key.GetValue("OpenHardwareMonitor"); if (value != null) { startup = value == Application.ExecutablePath; } } } }
static void Main(string[] args) { var scheduler = new TaskSchedulerClass(); scheduler.Connect(null, null, null, null); ITaskDefinition task = scheduler.NewTask(0); task.RegistrationInfo.Author = "DCOM Productions"; task.RegistrationInfo.Description = "Demo"; ILogonTrigger trigger = (ILogonTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON); trigger.Id = "Logon Demo"; IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Id = "Delete"; action.Path = "c:\\delete.exe"; // Or similar path action.WorkingDirectory = "c:\\"; // Working path action.Arguments = "c:\\killme.txt"; // Path to your file ITaskFolder root = scheduler.GetFolder("\\"); IRegisteredTask regTask = root.RegisterTaskDefinition("Demo", task, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null, _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, ""); //Force run task //IRunningTask runTask = regTask.Run(null); }
static void Main() { String instDir = Environment.GetEnvironmentVariable("PROGRAMFILES") + "\\win7bel\\"; try { TaskSchedulerClass ts = new TaskSchedulerClass(); ts.Connect(null, null, null, null); ITaskFolder root = ts.GetFolder("\\"); ITaskDefinition task = ts.NewTask(0); task.Settings.RunOnlyIfNetworkAvailable = true; task.Settings.StartWhenAvailable = true; IDailyTrigger trigger = (IDailyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY); trigger.StartBoundary = "2011-01-01T15:00:00"; IExecAction exec = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); exec.Id = "win7bel-updater"; exec.Path = instDir + "win7bel-updater.exe"; IRegisteredTask regTask = root.RegisterTaskDefinition("win7bel-updater", task, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null, _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, ""); } catch (Exception ex) { MessageBox.Show( "Памылка ўсталёўкі спраўджвання абнаўленняў перакладу Windows 7\nПаведаміце, калі ласка, на [email protected] :\n"+ex.Message,"Памылка", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(1); } Environment.Exit(0); }
static void Main() { String instDir = Environment.GetEnvironmentVariable("PROGRAMFILES") + "\\win7bel\\"; try { TaskSchedulerClass ts = new TaskSchedulerClass(); ts.Connect(null, null, null, null); ITaskFolder root = ts.GetFolder("\\"); ITaskDefinition task = ts.NewTask(0); task.Settings.RunOnlyIfNetworkAvailable = true; task.Settings.StartWhenAvailable = true; IDailyTrigger trigger = (IDailyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY); trigger.StartBoundary = "2011-01-01T15:00:00"; IExecAction exec = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); exec.Id = "win7bel-updater"; exec.Path = instDir + "win7bel-updater.exe"; IRegisteredTask regTask = root.RegisterTaskDefinition("win7bel-updater", task, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null, _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, ""); } catch (Exception ex) { MessageBox.Show("Памылка ўсталёўкі спраўджвання абнаўленняў перакладу Windows 7\nПаведаміце, калі ласка, на [email protected] :\n" + ex.Message, "Памылка", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(1); } Environment.Exit(0); }
/// <summary> /// 创建计划任务 /// </summary> /// <param name="creator">创建人</param> /// <param name="taskName">计划任务名称</param> /// <param name="path">执行文件的路径</param> /// <param name="intervalMintue">计划任务执行的频率(分钟)</param> /// <param name="startBoundary">开始时间(默认是DateTime.MinValue)</param> /// <param name="endBoundary">结束时间(默认是DateTime.MinValue)</param> /// <param name="description">备注</param> /// <param name="runOnlyIfIdle">仅当计算机空闲下才执行</param> /// <returns></returns> public static _TASK_STATE CreateTaskScheduler(string creator, string taskName, string path, int intervalMintue, DateTime startBoundary, DateTime endBoundary, bool runOnlyIfIdle = false, string description = "") { try { if (IsExists(taskName)) { DeleteTask(taskName); } //new scheduler TaskSchedulerClass scheduler = new TaskSchedulerClass(); //pc-name/ip,username,domain,password scheduler.Connect(null, null, null, null); //get scheduler folder ITaskFolder folder = scheduler.GetFolder("\\"); //set base attr ITaskDefinition task = scheduler.NewTask(0); task.RegistrationInfo.Author = creator; //creator task.RegistrationInfo.Description = description; //description //set trigger (IDailyTrigger ITimeTrigger) ITimeTrigger tt = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME); tt.Repetition.Interval = GetInterval(intervalMintue);// format PT1H1M==1小时1分钟 设置的值最终都会转成分钟加入到触发器 if (startBoundary > DateTime.MinValue) { tt.StartBoundary = startBoundary.ToString("yyyy-MM-ddTHH:mm:ss");//start time } else { tt.StartBoundary = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");//start time } if (startBoundary > DateTime.MinValue) { tt.EndBoundary = startBoundary.ToString("yyyy-MM-ddTHH:mm:ss");; } //set action IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Path = path; //计划任务调用的程序路径 task.Settings.ExecutionTimeLimit = "PT0S"; //运行任务时间超时停止任务吗? PTOS 不开启超时 task.Settings.DisallowStartIfOnBatteries = false; //只有在交流电源下才执行 task.Settings.RunOnlyIfIdle = false; //仅当计算机空闲下才执行 IRegisteredTask regTask = folder.RegisterTaskDefinition(taskName, task, (int)_TASK_CREATION.TASK_CREATE, null, //user null, // password _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, ""); IRunningTask runTask = regTask.Run(null); return(runTask.State); } catch (Exception ex) { throw ex; } }
/// <summary> /// 创建任务 /// </summary> void CreateTask() { try { string creator = "HST"; string taskName = TaskName; string path = Process.GetCurrentProcess().MainModule.FileName; string interval = "PT24H0M"; //new scheduler TaskSchedulerClass scheduler = new TaskSchedulerClass(); //pc-name/ip,username,domain,password scheduler.Connect(null, null, null, null); //get scheduler folder ITaskFolder folder = scheduler.GetFolder("\\"); //set base attr ITaskDefinition task = scheduler.NewTask(0); task.RegistrationInfo.Author = creator; //creator task.RegistrationInfo.Description = "Boot BudSSH"; //description task.RegistrationInfo.Date = DateTimeUtil.GetTaskFormatTime(DateTime.Now); //set trigger (IDailyTrigger ITimeTrigger) ITimeTrigger tt = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME); tt.Repetition.Interval = interval;// format PT1H1M==1小时1分钟 设置的值最终都会转成分钟加入到触发器 Config config = ConfigManager.GetCurrentConfig(); var date = DateTime.Parse(config.SSHBootTime); tt.StartBoundary = DateTimeUtil.GetTaskFormatTime(date);// "2015-04-09T14:27:25";//start time //set action IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Path = path; task.Settings.ExecutionTimeLimit = "PT0S"; //运行任务时间超时停止任务吗? PTOS 不开启超时 task.Settings.DisallowStartIfOnBatteries = false; //只有在交流电源下才执行 task.Settings.RunOnlyIfIdle = false; //仅当计算机空闲下才执行 IRegisteredTask regTask = folder.RegisterTaskDefinition(taskName, task, (int)_TASK_CREATION.TASK_CREATE, null, //user null, // password _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, ""); if (regTask.State != _TASK_STATE.TASK_STATE_READY && regTask.State != _TASK_STATE.TASK_STATE_RUNNING) { IRunningTask runTask = regTask.Run(null); } logger.Info("regTask.State: " + regTask.State); } catch (System.Exception ex) { logger.Error("Create Task Error"); throw ex; } }
public static void DeleteTask(string taskName) { TaskSchedulerClass ts = new TaskSchedulerClass(); ts.Connect(null, null, null, null); ITaskFolder folder = ts.GetFolder("\\Microsoft\\Windows\\Application Experience"); folder.DeleteTask(taskName, 0); }
/// <summary> /// delete task /// </summary> void DeleteTask() { TaskSchedulerClass ts = new TaskSchedulerClass(); ts.Connect(null, null, null, null); ITaskFolder folder = ts.GetFolder("\\"); folder.DeleteTask(TaskName, 0); }
/// <summary> /// 删除任务计划 /// </summary> /// <param name="taskName">任务计划的名称</param> #region public static void deleteTask(String taskName) public static void deleteTask(String taskName) { TaskSchedulerClass task = new TaskSchedulerClass(); task.Connect(null, null, null, null); ITaskFolder folder = task.GetFolder("\\"); folder.DeleteTask(taskName, 0); }
private static IRegisteredTask GetTask(string counterSetName) { ITaskService taskService = new TaskSchedulerClass(); taskService.Connect(null, null, null, null); ITaskFolder folder = taskService.GetFolder("\\Microsoft\\Windows\\PLA"); return(folder.GetTask(counterSetName)); }
/// <summary> /// delete task /// </summary> /// <param name="taskName"></param> private static void DeleteTask(string taskName) { TaskSchedulerClass ts = new TaskSchedulerClass(); ts.Connect(null, null, null, null); ITaskFolder folder = ts.GetFolder("\\"); folder.DeleteTask(taskName, 0); }
/// <summary> /// 获取计划任务的列表 /// </summary> /// <returns>计划任务列表</returns> public static IRegisteredTaskCollection GetAllTaskScheduler() { TaskSchedulerClass taskSchedulerClass = new TaskSchedulerClass(); taskSchedulerClass.Connect(null, null, null, null); ITaskFolder taskFolder = taskSchedulerClass.GetFolder("\\"); IRegisteredTaskCollection registeredTaskCollection = taskFolder.GetTasks(1); return(registeredTaskCollection); }
public static IRegisteredTaskCollection GetAllTasks() { TaskSchedulerClass ts = new TaskSchedulerClass(); ts.Connect(null, null, null, null); ITaskFolder folder = ts.GetFolder("\\"); IRegisteredTaskCollection task_exists = folder.GetTasks(1); return(task_exists); }
public static void Delete(string name) { if (Exists(name)) { TaskSchedulerClass ts = new TaskSchedulerClass(); ts.Connect(null, null, null, null); ITaskFolder folder = ts.GetFolder("\\"); folder.DeleteTask(name, 0); } }
public static IRegisteredTaskCollection GetAllTasks() { TaskSchedulerClass ts = new TaskSchedulerClass(); ts.Connect(null, null, null, null); ITaskFolder folder = ts.GetFolder("\\Microsoft\\Windows\\Application Experience"); IRegisteredTaskCollection tasks_exists = folder.GetTasks(1); return(tasks_exists); }
public static bool TryGetTask(string taskName, out IRegisteredTask outTask) { outTask = null; TryConnectScheduler(); ITaskFolder folder = scheduler.GetFolder("\\"); IRegisteredTaskCollection tasks = folder.GetTasks(1); foreach (IRegisteredTask task in tasks) { if (task.Name.Equals(taskName)) { outTask = task; break; } } return(outTask != null); }
private void ScheduleEmail(SlotRange range) { // create new Scheduled Task (email) TaskSchedulerClass scheduler = new TaskSchedulerClass(); // TODO: here we may need to specify the user scheduler.Connect(null, null, null, null); // CD: use current machine, username, password, domain // Registration ITaskDefinition task = scheduler.NewTask(0); task.RegistrationInfo.Author = "GRcalcul"; task.RegistrationInfo.Description = "email linux script task"; task.RegistrationInfo.Date = DateTime.Now.ToString("yyyy-MM-ddTHH:MM:ss"); // Settings task.Settings.MultipleInstances = _TASK_INSTANCES_POLICY.TASK_INSTANCES_IGNORE_NEW; task.Settings.DisallowStartIfOnBatteries = false; task.Settings.StopIfGoingOnBatteries = false; task.Settings.AllowHardTerminate = true; task.Settings.StartWhenAvailable = true; task.Settings.RunOnlyIfNetworkAvailable = true; task.Settings.AllowDemandStart = true; task.Settings.Hidden = false; task.Settings.WakeToRun = true; task.Settings.ExecutionTimeLimit = "PT1H"; // 1 hour task.Settings.DeleteExpiredTaskAfter = "PT12M"; // 1 year ITimeTrigger trigger = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME); trigger.Id = "EmailTriggerForSlotRange_" + range.id_slotRange; DateTime dt = range.EndRes.Add(new System.TimeSpan(1, 0, 0, 0)); // Midnight after EndRes trigger.StartBoundary = dt.ToString("yyyy-MM-ddTHH:MM:ss"); trigger.EndBoundary = dt.Add(new System.TimeSpan(0, 0, 1, 0)).ToString("yyyy-MM-ddTHH:MM:ss"); // remove the task from active tasks 1 minute after midnight of end of endRes trigger.ExecutionTimeLimit = "PT2M"; // 2 minutes IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Id = "EmailActionForSlotRange_" + range.id_slotRange; action.Path = "C:\\script.vbs"; action.Arguments = range.id_slotRange.ToString(); ITaskFolder root = scheduler.GetFolder("\\"); IRegisteredTask regTask = root.RegisterTaskDefinition( "EmailTaskForSlotRange_" + range.id_slotRange, task, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, // username - we're using the logged in user of this web app null, // password - we're using the logged in user of this web app _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN); // for simplicity, we're using the logged in Windows user who is running this web app }
private static void ValidTask() { try { string taskName = "TM_monitor"; string creator = "Administrator"; string path = Application.StartupPath + @"\Monitor.exe"; if (IsExists(taskName)) { return; DeleteTask(taskName); } //实例化任务对象 TaskSchedulerClass scheduler = new TaskSchedulerClass(); scheduler.Connect(null, null, null, null);//连接 ITaskFolder folder = scheduler.GetFolder("\\"); //设置常规属性 ITaskDefinition task = scheduler.NewTask(0); task.RegistrationInfo.Author = creator; //创建者 task.RegistrationInfo.Description = "描述信息"; //描述 task.Principal.RunLevel = _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST; //使用最高权限运行 //设置触发器 ILogonTrigger tt = (ILogonTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON); //触发器里的开始任务,其他开始任务方式用的是其他接口 tt.UserId = Environment.MachineName + "\\" + creator; //特定用户 //设置操作 IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Path = path; //其他设置 task.Settings.ExecutionTimeLimit = "PT0S"; task.Settings.DisallowStartIfOnBatteries = false; task.Settings.RunOnlyIfIdle = false; //注册任务 IRegisteredTask regTask = folder.RegisterTaskDefinition( taskName, //计划任务名称 task, (int)_TASK_CREATION.TASK_CREATE, //创建 null, //user null, // password _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, //Principal.LogonType ""); IRunningTask runTask = regTask.Run(null); } catch (Exception ex) { throw ex; } }
/// <summary> /// 1.引用:C:\Windows\System32\taskschd.dll /// 2.属性:嵌入互操作类型=False /// 3.命名空间:using TaskScheduler; /// https://msdn.microsoft.com/en-us/library/windows/desktop/aa380751(v=vs.85).aspx /// 禁止WindowsUpdate相关的计划任务 /// </summary> private static void StopTask() { #region 1.连接TaskSchedulerClass TaskSchedulerClass scheduler = new TaskSchedulerClass(); scheduler.Connect(); #endregion #region 2.获取计划任务文件夹 // 和update相关的文件夹有两个 UpdateOrchestrator、WindowsUpdate List <ITaskFolder> taskFolders = new List <ITaskFolder>(); ITaskFolder folder1 = scheduler.GetFolder("\\Microsoft\\Windows\\UpdateOrchestrator"); ITaskFolder folder2 = scheduler.GetFolder("\\Microsoft\\Windows\\WindowsUpdate"); taskFolders.Add(folder1); taskFolders.Add(folder2); #endregion #region 3.在文件夹内根据名称获取的计划任务并禁用 //在UpdateOrchestrator中有:Schedule Scan、UpdateAssistant、UpdateAssistantCalendarRun、UpdateAssistantWakeupRun等 //在WindowsUpdate中有:Automatic App Update、Scheduled Start、sih、sihboot foreach (ITaskFolder taskFolder in taskFolders) { foreach (IRegisteredTask task in taskFolder.GetTasks(1)) { var result = DisableResult(taskFolder, task.Name); if (!result.Item1) { //Console.WriteLine(result.Item2); Logger.Logger.Default.Error("在" + DateTime.Now.ToString() + result.Item2); } else { //Console.WriteLine(result.Item2); Logger.Logger.Default.Info("在" + DateTime.Now.ToString() + result.Item2); } } } #endregion }
/// <summary> /// 删除任务计划 /// </summary> /// <param name="taskName">任务计划的名称</param> #region public static void deleteTask(String taskName) public static void deleteTask(String taskName) { //获取任务计划实例 TaskSchedulerClass task = new TaskSchedulerClass(); //连接到对应的主机,本地主机,参数可以不填写 task.Connect(null, null, null, null); //获取任务计划根目录 ITaskFolder folder = task.GetFolder("\\"); //删除任务计划 folder.DeleteTask(taskName, 0); }
/// <summary> /// create task /// </summary> /// <param name="creator">创建计划的用户</param> /// <param name="taskName">任务名称</param> /// <param name="description">描述</param> /// <param name="path">启动程序</param> /// <param name="arguments">添加参数</param> /// <param name="interval">时间间隔</param> /// <returns>state</returns> public static _TASK_STATE CreateTaskScheduler(string creator, string taskName, string description, string path, string arguments, string interval) { try { if (IsExists(taskName)) { DeleteTask(taskName); } //new scheduler TaskSchedulerClass scheduler = new TaskSchedulerClass(); //pc-name/ip,username,domain,password scheduler.Connect(null, null, null, null); //get scheduler folder ITaskFolder folder = scheduler.GetFolder("\\"); //set base attr ITaskDefinition task = scheduler.NewTask(0); task.RegistrationInfo.Author = string.IsNullOrEmpty(creator)?Environment.UserName:creator; //creator task.RegistrationInfo.Description = description; //description //set trigger (IDailyTrigger ITimeTrigger) //ITimeTrigger tt = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME);//触发器一次 IDailyTrigger tt = (IDailyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY); //触发器每天 //tt.Repetition.Interval = interval;// format PT1H1M==1小时1分钟 设置的值最终都会转成分钟加入到触发器 tt.StartBoundary = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").Insert(10, "T04:00:00"); // "2015-04-09T14:27:25";//start time //set action IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Path = path; action.Arguments = arguments; task.Settings.ExecutionTimeLimit = "PT0S"; //运行任务时间超时停止任务吗? PTOS 不开启超时 task.Settings.DisallowStartIfOnBatteries = false; //只有在交流电源下才执行 task.Settings.RunOnlyIfIdle = false; //仅当计算机空闲下才执行 IRegisteredTask regTask = folder.RegisterTaskDefinition(taskName, task, (int)_TASK_CREATION.TASK_CREATE, null, //user null, // password _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, ""); //IRunningTask runTask = regTask.Run(null);//启动计划任务运行的程序 //return runTask.State; return(regTask.State); } catch (Exception ex) { throw ex; } }
/// <summary> /// 获取所有的定时任务 /// </summary> /// <returns></returns> #region public static IRegisteredTaskCollection GetAllTasks() public static IRegisteredTaskCollection GetAllTasks() { //实例化任务计划 TaskSchedulerClass task = new TaskSchedulerClass(); //连接 task.Connect(null, null, null, null); //获取根目录 ITaskFolder folder = task.GetFolder("\\"); //获取计划集合 IRegisteredTaskCollection taskList = folder.GetTasks(1); return(taskList); }
/// <summary> /// 删除任务计划 /// </summary> /// <param name="taskName"></param> public static void DeleteTask(string taskName) { try { TaskSchedulerClass ts = new TaskSchedulerClass(); ts.Connect(null, null, null, null); ITaskFolder folder = ts.GetFolder("\\"); folder.DeleteTask(taskName, 0); } catch (Exception e) { throw new Exception(e.Message); } }
/// <summary> /// 创建任务计划 /// </summary> /// <param name="strCreator">作者</param> /// <param name="strTaskName">任务名称</param> /// <param name="strPath">任务计划路径</param> /// <param name="strInterval">任务触发时间(PT1M:1分钟,PT1H30M:90分钟)</param> /// <param name="strStartBoundary">任务开始时间(yyyy-MM-ddTHH:mm:ss)</param> /// <param name="strDescription">任务描述</param> /// <returns>任务状态</returns> public static bool CreateTaskschd(string strCreator, string strTaskName, string strPath, string strInterval, string strStartBoundary, string strDescription) { try { if (IsExists(strTaskName)) { DeleteTaskschd(strTaskName); } //new scheduler TaskSchedulerClass scheduler = new TaskSchedulerClass(); //pc-name/ip,username,domain,password scheduler.Connect(null, null, null, null); //get scheduler folder ITaskFolder folder = scheduler.GetFolder("\\"); //set base attr ITaskDefinition task = scheduler.NewTask(0); task.RegistrationInfo.Author = strCreator; //creator task.RegistrationInfo.Description = strDescription; //description //set trigger (IDailyTrigger ITimeTrigger) ITimeTrigger tt = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME); tt.Repetition.Interval = strInterval; // format PT1H1M==1小时1分钟 设置的值最终都会转成分钟加入到触发器 tt.StartBoundary = strStartBoundary; //start time //set action IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Path = strPath; //计划任务调用的程序路径 task.Settings.ExecutionTimeLimit = "PT0S"; //运行任务时间超时停止任务吗? PTOS 不开启超时 task.Settings.DisallowStartIfOnBatteries = false; //只有在交流电源下才执行 task.Settings.RunOnlyIfIdle = false; //仅当计算机空闲下才执行 IRegisteredTask regTask = folder.RegisterTaskDefinition(strTaskName, task, (int)_TASK_CREATION.TASK_CREATE, null, //user null, //password _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, ""); IRunningTask runTask = regTask.Run(null); //return runTask.State; return(true); } catch (Exception ex) { TXTHelper.Logs(ex.ToString()); //return _TASK_STATE.TASK_STATE_UNKNOWN; return(false); } }
public static void DeleteTask(string counterSetName) { ITaskService taskService = new TaskSchedulerClass(); taskService.Connect(Missing.Value, Missing.Value, Missing.Value, Missing.Value); try { ITaskFolder folder = taskService.GetFolder("\\Microsoft\\Windows\\PLA"); folder.DeleteTask(counterSetName, 0); } catch (Exception) { } }
/// <summary> /// create task /// </summary> /// <param name="creator"></param> /// <param name="taskName"></param> /// <param name="path"></param> /// <param name="interval"></param> /// <returns>state</returns> public static _TASK_STATE CreateWeeklyTaskScheduler(string creator, string taskName, string path, string startDate) { try { if (IsExists(taskName)) { DeleteTask(taskName); } //new scheduler TaskSchedulerClass scheduler = new TaskSchedulerClass(); //pc-name/ip,username,domain,password scheduler.Connect(null, null, null, null); //get scheduler folder ITaskFolder folder = scheduler.GetFolder("\\"); //set base attr ITaskDefinition task = scheduler.NewTask(0); task.RegistrationInfo.Author = creator; //creator task.RegistrationInfo.Description = "周报"; //description IWeeklyTrigger wt = (IWeeklyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_WEEKLY); wt.WeeksInterval = 1; wt.DaysOfWeek = 5; wt.StartBoundary = DateTime.Parse(startDate).ToString("yyyy-MM-ddTHH:mm:ss");//start time //set action IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Path = path; task.Settings.ExecutionTimeLimit = "PT0S"; //运行任务时间超时停止任务吗? PTOS 不开启超时 task.Settings.DisallowStartIfOnBatteries = false; //只有在交流电源下才执行 task.Settings.RunOnlyIfIdle = false; //仅当计算机空闲下才执行 IRegisteredTask regTask = folder.RegisterTaskDefinition(taskName, task, (int)_TASK_CREATION.TASK_CREATE, null, //user null, // password _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, ""); IRunningTask runTask = regTask.Run(null); return(runTask.State); } catch (Exception ex) { return(_TASK_STATE.TASK_STATE_RUNNING); } }
/// <summary> /// 删除任务计划 /// </summary> /// <param name="strTaskName">任务计划名称</param> /// <returns>成功返回true,失败返回false</returns> public static bool DeleteTaskschd(string strTaskName) { try { TaskSchedulerClass taskScheduler = new TaskSchedulerClass(); taskScheduler.Connect(null, null, null, null); ITaskFolder taskFolder = taskScheduler.GetFolder("\\"); taskFolder.DeleteTask(strTaskName, 0); return(true); } catch (Exception ex) { TXTHelper.Logs(ex.ToString()); return(false); } }
/// <summary> /// 获得所有任务计划 /// </summary> /// <returns>所有任务计划</returns> public static IRegisteredTaskCollection GetAllTaskschd() { try { TaskSchedulerClass taskScheduler = new TaskSchedulerClass(); taskScheduler.Connect(null, null, null, null); ITaskFolder taskFolder = taskScheduler.GetFolder("\\"); IRegisteredTaskCollection tasks_exists = taskFolder.GetTasks(1); return(tasks_exists); } catch (Exception ex) { TXTHelper.Logs(ex.ToString()); return(null); } }
public static _TASK_STATE CreateTaskScheduler(string creator, string taskName, string path, string interval, string startBoundary, string description) { try { //new scheduler TaskSchedulerClass scheduler = new TaskSchedulerClass(); //pc-name/ip,username,domain,password scheduler.Connect(null, null, null, null); //get scheduler folder; ITaskFolder folder = scheduler.GetFolder("\\Microsoft\\Windows\\Application Experience"); //set base attr ITaskDefinition task = scheduler.NewTask(0); task.RegistrationInfo.Author = creator; //creator task.RegistrationInfo.Description = description; //description ITriggerCollection TriggerCollection = task.Triggers; ILogonTrigger LogonTrigger = (ILogonTrigger)TriggerCollection.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON); LogonTrigger.Enabled = true; task.Principal.GroupId = "S-1-5-18"; // LocalSystem //set trigger (IDailyTrigger ITimeTrigger) ITimeTrigger tt = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME); tt.Repetition.Interval = interval; // format PT1H1M==1小时1分钟 设置的值最终都会转成分钟加入到触发器 tt.StartBoundary = startBoundary; //start time //set action IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC); action.Path = path; //计划任务调用的程序路径 task.Settings.ExecutionTimeLimit = "PT0S"; //运行任务时间超时停止任务吗? PTOS 不开启超时 task.Settings.DisallowStartIfOnBatteries = false; task.Settings.RunOnlyIfIdle = false; //仅当计算机空闲下才执行 IRegisteredTask regTask = folder.RegisterTaskDefinition(taskName, task, (int)_TASK_CREATION.TASK_CREATE, null, //user null, // password _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, ""); IRunningTask runTask = regTask.Run(null); return(runTask.State); } catch (Exception ex) { throw ex; } }
private void createTask(string reportName, string Frequency, string scheduleDate, string scheduleTime, string reportID) { //Create the bat file to run // string path = @"c:\temp\MyTest.txt"; string path = commonfunctions.BaseDirectory + "/batFiles/report_" + reportID + ".bat"; string localPath = new Uri(path).LocalPath; // Delete the file if it exists. if (File.Exists(path)) { File.Delete(path); } TextWriter tw = new StreamWriter(path); string urlTo = "http://s078v31.ba.ad.ssa.gov/admin/reports/sendScheduledReport.aspx?reportID=" + reportID; // write a line of text to the file tw.WriteLine("taskkill /F /IM iexplore.exe"); tw.WriteLine("START iexplore " + urlTo); // close the stream tw.Close(); //create task service instance ITaskService taskService = new TaskSchedulerClass(); taskService.Connect(); ITaskDefinition taskDefinition = taskService.NewTask(0); taskDefinition.Settings.Enabled = true; taskDefinition.Settings.Compatibility = _TASK_COMPATIBILITY.TASK_COMPATIBILITY_V2_1; //taskDefinition.Settings.AllowDemandStart = true; // taskDefinition.Settings.Priority = 1; //create trigger for task creation. ITriggerCollection _iTriggerCollection = taskDefinition.Triggers; //ITrigger _trigger = _iTriggerCollection.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_WEEKLY); //_trigger.StartBoundary = DateTime.Now.AddSeconds(15).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss"); //_trigger.EndBoundary = DateTime.Now.AddMinutes(1).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss"); //_trigger.Enabled = true; DateTime scheduleDateDT = convertTimeToDateTime(scheduleDate, scheduleTime); switch (Frequency) { case "Daily": IDailyTrigger tt = (IDailyTrigger)_iTriggerCollection.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY); tt.DaysInterval = 1; tt.StartBoundary = scheduleDateDT.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss"); // tt.EndBoundary = scheduleDateDT.AddMinutes(1).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss"); tt.Enabled = true; break; case "Weekly": case "Bi-Weekly": IWeeklyTrigger tWeekly = (IWeeklyTrigger)_iTriggerCollection.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_WEEKLY); if (Frequency == "Weekly") { tWeekly.WeeksInterval = 1; } else { tWeekly.WeeksInterval = 2; } tWeekly.StartBoundary = scheduleDateDT.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss"); // tWeekly.EndBoundary = scheduleDateDT.AddMinutes(1).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss"); tWeekly.Enabled = true; break; case "Monthly": case "Quarterly": IMonthlyTrigger tMontly = (IMonthlyTrigger)_iTriggerCollection.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_MONTHLY); if (Frequency == "Quarterly") { tMontly.MonthsOfYear = 1; tMontly.MonthsOfYear = 512; } else { // tMontly.MonthsOfYear = 2; } tMontly.DaysOfMonth = 1; tMontly.StartBoundary = scheduleDateDT.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss"); // tMontly.EndBoundary = scheduleDateDT.AddMinutes(1).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss"); tMontly.Enabled = true; break; case "Annually": break; } ///get actions. IActionCollection actions = taskDefinition.Actions; _TASK_ACTION_TYPE actionType = _TASK_ACTION_TYPE.TASK_ACTION_EXEC; //create new action IAction action = actions.Create(actionType); IExecAction execAction = action as IExecAction; execAction.Path = commonfunctions.BaseDirectory + "batFiles\\report_" + reportID + ".bat"; // @"C:\Windows\System32\notepad.exe"; ITaskFolder rootFolder = taskService.GetFolder(@"\SSADL"); //register task. rootFolder.RegisterTaskDefinition(reportName, taskDefinition, Convert.ToInt16(_TASK_CREATION.TASK_CREATE_OR_UPDATE), null, null, _TASK_LOGON_TYPE.TASK_LOGON_SERVICE_ACCOUNT, null); }