Use C # to create a scheduled Task (How to create a Task scheduse use C #),

Source: Internet
Author: User
Tags repetition schtasks

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.

 

  •  Requirement: Run multiple background programs (winfrom, wpf, console, and so on) in an indefinite period of time to update data.
  • Problem: Why do we need to use a scheduled task instead of simply using a timer in the program?

    • A: The most obvious thing is that the Timer Program is always running in the background, but it only needs to run once a day or once a month. It's not a waste of CPU resources to keep running timing in the background.
  • Solution:
    • You can see in the control panel using the scheduled tasks that come with windows to manually create a scheduled task.
    • Use the built-in Microsoft class library TaskScheduler ("c: \ windows \ system32 \ taskachd. dll") to create
    • Use the Process. Star () doscommand to create a scheduled task
      • Run the following command to run scheduler.exe:

        Schtasks/create/SC minute/mo 1/tn MyTask/tr calc.exe/st // run notepad once every minute from

        You can enter the following information in the cmd command box:

        > Schtasks /?

        > Schtasks/create /?

        > Schtasks/delete /?

        > Schtasks/query /?

        > Schtasks/change /?

      • You can also refer to: https://msdn.microsoft.com/en-us/library/windows/desktop/bb736357%28v=vs.85%29.aspx

 

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!

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.