Use C # to create a scheduled Task (How to create a Task scheduse use C #),
This article describes how to use C # To create a windows scheduled task.
Solution start:
In this example, the TaskScheduler class library comes with Microsoft. The encapsulated code below includes deleting a scheduler task, determining whether a scheduler task exists, obtaining all scheduler tasks, and creating a scheduler task. (For details, see the Notes ):
Obtain the list of scheduled tasks:
/// <Summary> /// get all tasks /// </summary> public static IRegisteredTaskCollection GetAllTasks () {TaskSchedulerClass ts = new TaskSchedulerClass (); ts. connect (null, null); ITaskFolder folder = ts. getFolder ("\"); IRegisteredTaskCollection tasks_exists = folder. getTasks (1); return tasks_exists ;}View Code
Determine whether a scheduled task exists:
/// <Summary> /// check task isexists // </summary> /// <param name = "taskName"> </param> /// <returns> </returns> public static bool IsExists (string taskName) {var isExists = false; IRegisteredTaskCollection tasks_exists = GetAllTasks (); for (int I = 1; I <= tasks_exists.Count; I ++) {IRegisteredTask t = tasks_exists [I]; if (t. name. equals (taskName) {isExists = true; break ;}} return isExists ;}View Code
Delete a scheduled task:
/// <Summary> /// delete task /// </summary> /// <param name = "taskName"> </param> private static void DeleteTask (string taskName) {TaskSchedulerClass ts = new TaskSchedulerClass (); ts. connect (null, null); ITaskFolder folder = ts. getFolder ("\"); folder. deleteTask (taskName, 0 );}View Code
Create a scheduled task:
/// <Summary> /// create scheduler /// </summary> /// <param name = "creator"> </param> /// <param name = "taskName"> </param> // <param name = "path"> </param> // <param name = "interval"> </param> // /<param name = "startBoundary"> </param> // <param name = "description"> </param> // <returns> </returns> public static _ TASK_STATE createtaskschedator (string creator, string taskName, string path, string interval, s Tring startBoundary, string description) {try {if (IsExists (taskName) {DeleteTask (taskName);} // new scheduler TaskSchedulerClass scheduler = new TaskSchedulerClass (); // pc-name/ip, username, domain, password scheduler. connect (null, null); // get scheduler folder ITaskFolder folder = schedder. getFolder ("\"); // set base attr ITaskDefinition task = schedtion. newTask (0); task. registratio NInfo. 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 = interval; // format PT1H1M = 1 hour the value set in 1 minute will be converted to minutes and added to the trigger tt. startBoundary = startBoundary; // start time // set action IExecAction action = (IExecActio N) task. actions. create (_ TASK_ACTION_TYPE.TASK_ACTION_EXEC); action. path = path; // The program Path called by the scheduled task. settings. executionTimeLimit = "PT0S"; // does the running task time out to stop the task? PTOS does not enable time-out tasks. settings. disallowStartIfOnBatteries = false; // The task is executed only in the AC power supply. settings. runOnlyIfIdle = false; // IRegisteredTask regTask = folder is executed only when the computer is idle. 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 ;}}View Code
Complete code:
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using TaskScheduler; namespace McodsBgManager {public class SchTaskExt {// <summary> // delete task /// </summary> /// <param name = "taskName"> </param> private static void DeleteTask (string taskName) {TaskSchedulerClass ts = new TaskSchedulerClass (); ts. connect (null, null); I TaskFolder folder = ts. getFolder ("\"); folder. deleteTask (taskName, 0);} // <summary> // get all tasks /// </summary> public static IRegisteredTaskCollection GetAllTasks () {TaskSchedulerClass ts = new TaskSchedulerClass (); ts. connect (null, null); ITaskFolder folder = ts. getFolder ("\"); IRegisteredTaskCollection tasks_exists = folder. getTasks (1); return tasks_exists;} // <summary> /// Check task isexists /// </summary> /// <param name = "taskName"> </param> /// <returns> </returns> public static bool IsExists (string taskName) {var isExists = false; IRegisteredTaskCollection tasks_exists = GetAllTasks (); for (int I = 1; I <= tasks_exists.Count; I ++) {IRegisteredTask t = tasks_exists [I]; if (t. name. equals (taskName) {isExists = true; break;} return isExists;} // <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 CreateTaskScheduler (string creator, string taskName, string path, string interval) {try {if (IsExists (taskName) {DeleteTask (taskName);} // new scheduler TaskSchedulerClass Scheduler = new TaskSchedulerClass (); // pc-name/ip, username, domain, password scheduler. connect (null, null); // get scheduler folder ITaskFolder folder = schedder. getFolder ("\"); // set base attr ITaskDefinition task = schedtion. newTask (0); task. registrationInfo. author = "McodsAdmin"; // creator task. registrationInfo. description = "... "; // description // set trigger (IDailyTrigger ITimeTrig Ger) ITimeTrigger tt = (ITimeTrigger) task. triggers. create (_ TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME); tt. repetition. interval = interval; // format PT1H1M = 1 hour the value set in 1 minute will be converted to minutes and added to the trigger tt. startBoundary = "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"; // run Does the row task time-out stop the task? PTOS does not enable time-out tasks. settings. disallowStartIfOnBatteries = false; // The task is executed only in the AC power supply. settings. runOnlyIfIdle = false; // IRegisteredTask regTask = folder is executed only when the computer is idle. 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 ;}}}}View Code
How can I use SchTaskExt. cs encapsulated?
The btnSetup_Click code is as follows: This example uses calc.exe.
Private void btnSetup_Click (object sender, RoutedEventArgs e) {// creator var creator = "Tianyou"; // scheduler Task Name var taskName = "CalcTask "; // run the program path var path = "C: \ Windows \ System32 \ calc.exe "; // scheduled task execution frequency pt11m one minute PT1H30M 90 minutes var interval = "PT1M"; // the start time must follow yyyy-MM-ddTHH: mm: ss format var startBoundary = "2015-04-09T14: 27: 25"; var description = "this is the plan description abc"; _ TASK_STATE state = SchTaskExt. createTaskScheduler (cr Eator, taskName, path, interval, startBoundary, description); if (state = _ TASK_STATE.TASK_STATE_RUNNING) {MessageBox. Show ("the scheduled task is successfully deployed! ");}}
After running successfully:
As you can see, calc.exe is running. Next we can find the scheduled task window in the control panel.
All done!
Note::
1After referencing taskachd. dll, select and press F4 to change the embedded interoperability type to False in the attribute (if not set, an error will be reported: The interoperability type "TaskScheduler. TaskSchedulerClass" cannot be embedded ". Use the applicable interface instead. )
2. All operations need to be instantiated after schdule connection: schdule. Connec ("pc-name or ip", "username", "domain", "password ")
3There are multiple options for the trigger type (by day IDailyTrigger, by minute ITimeTrigger ));
The format of the trigger frequency (Interval) must follow the format of "PT1H1M;
The start time must follow the format "YYYY-MM-DDThh: mm: ss.
4. The scheduled task running instance seems to be only unique, because currently this calc can run normally for the first time, and the second request is denied:
The operator or system administrator rejects the request. (0x800710E0). No solution is found for this error on the Internet, for example.
Later, I found this solution on the Internet, but it still failed to be solved after setting it. The official website does not have this error code (click here to view the Task Scheduler ).
Therefore, I understand that this scheduled task can only run one instance. If the scheduled task reaches the next trigger cycle before the instance ends, the request will be rejected.
In addition, please specify other interpretations. Thank you very much!
Complete!