Task Scheduler in C#.Net


This article describes a way to create the Scheduled tasks in a system pro-grammatically for Windows Vista, Windows 7 etc Operating Systems using C#.NET language. Windows operating systems, though, already provide a User Interface to see a complete list, to add, to update or to delete a Scheduled Task under it. This UI can be seen by launching a Computer Management by issuing a command compmgmt.msc on a command prompt.

System Requirements
Windows Vista or Windows 7 or higher versions Operating systems

Development Environment

  • Development IDE – Visual Studio [or simple Notepad]
  • Task Scheduler COM Library

How to Implement?
To begin with, we need an underlying library, can be COM library or unmanaged C(++) library or managed wrapper which talks to the system to get things done.
Aaannnnnnnn.
Don’t worry.
Here is the trick.
If you dare to 🙂 browse to C:\Windows\syswow64, you will notice the presence of Taskschd.dll assembly. This is what we need to proceed with.

Steps:

  1. Create a new Project using Visual Studio
  2. Right Click on project and click Add Reference.Select “TaskScheduler TypeLibrary”

The last step resulted in an Interop assembly generation and referenced in the project. You can check this by selecting a referenced assembly and viewing it’s properties.

Now, we’ll make use of Types defined/exported in the interop assembly to achieve:
– View the list of all Scheduled Tasks
– To pro-grammatically add a Scheduled Task
– To delete a task

Be it any CRUD operation, we’ll make use of ITaskService type which connects to an actual store and exposes the operations. We’ll instantiate the TaskService and call the Connect method before any valid operation.

Before detailing out the steps, another important aspect is to understand the layout or a structure, the tasks are organized.

Scheduled Tasks are organized in a hierarchical fashion. They are always stored in a folder. The very first folder is termed Root Folder with a path @”\” or “\\”. Each folder can have sub folders under it. View the above picture to understand or open “Scheduled Tasks” on your system.

The following sections detail out “How to ?” part for each operation.

How to retrieve the list of all Scheduled Tasks?

  1. Instantiate TaskService object.
    ITaskService taskService = new TaskScheduler();
  2. Call Connect() on previously created taskService object.
    taskService.Connect();
  3. Get a reference to Root Folder.
    ITaskFolder rootFolder = taskService.GetFolder(@"\");
    Remember, path to Root Folder is “\”.
  4. Make a call to GetTasks() on a folder.
    IRegisteredTaskCollection tasks = rootFolder.GetTasks(0); // 0 or 1: 1 will include all hidden tasks as well
    Note: Here, you will get those tasks only which are created in root folder. Since this root folder can have sub folders under it, you have to recursively call GetTasks() for each sub-folder.

    private void Load()
    {
    ITaskService taskService = new TaskScheduler();
    taskService.Connect();List<IRegisteredTask> tasks = new List<IRegisteredTask>();

    // “\\” or @”\” is the RootFolder
    this.GetData(taskService.GetFolder(@”\”), tasks);

    this.view.ScheduledTasks = tasks;
    }

    private void GetData(ITaskFolder folder, List tasks)
    {
    foreach (IRegisteredTask task in folder.GetTasks(1)) // get all tasks including those which are hidden, otherwise 0
    {
    tasks.Add(task);

    System.Runtime.InteropServices.Marshal.ReleaseComObject(task); // release COM object

    foreach (ITaskFolder subFolder in folder.GetFolders(1))
    {
    this.GetData(subFolder, tasks);
    }
    }
    System.Runtime.InteropServices.Marshal.ReleaseComObject(folder);
    }

How to delete a Scheduled Task?
We need some task details like task name, task container i.e. folder in which this task exists in order to delete it.
By default, each task’s Location property contains the Name of that particular task as well as it’s containing folder. So if we have an access to Task Location only, we can find out it’s name and it’s containing folder through some string manipulation.
For e.g., “\\SampleTaskFolder\\SampleTask” means that the task named SampleTask is stored in a folder SampleTaskFolder which is further in RootFolder(“\\”).
Steps to delete a task when it’s full location is provided as input:

  • Find out the name of Task and it’s containing folder through string manipulation. [You may want to Validate the input:task Location]
  • Instantiate a task service and connect
  • Get the containing folder reference through below code:
    ITaskFolder containingFolder = taskService.GetFolder(folderPath);
  • Call DeleteTask() with a task name
    containingFolder.DeleteTask(taskName, 0);

This is how a complete function may Look like:

public bool DeleteTask(string taskPath)
{
ITaskService taskService = new TaskScheduler();
taskService.Connect();ValidateTaskPath(taskPath);

int lastIndex = taskPath.LastIndexOf(“\\”);

string folderPath = taskPath.Substring(0, lastIndex);

if (string.IsNullOrWhiteSpace(folderPath))
{
folderPath = “\\”;
}

string taskName = taskPath.Substring(lastIndex + 1);

try
{
ITaskFolder containingFolder = taskService.GetFolder(folderPath);

containingFolder.DeleteTask(taskName, 0);
}
catch(FileNotFoundException exception)
{
throw new InvalidTaskPath(“Task Path is invalid”, exception);
}

return true;
}

How to create\update a Scheduled task?
Creating a Scheduled task is not as easy as other operations. Before i detail out the steps here, i am pinpointing few things which are expected by COM and it’s behavior, to get our new task registered successfully in the system.

  • Name of a new Task to be created can be empty while doing registration. If this is the case, system will generate a GUID and assign this as a name of a task
  • The ExecutionTimeLimit, IdleDuration parameters under ITaskDefinition [see “Possible error and exceptions” section below] should be in a particular format. If this is not the case, new task won’t be registered
  • Atleast one action should be specified when registering a new task
  • If a task with the same name under the same folder exists, it will be updated if you register a task with a flag: “CreateOrUpdate” has a value of ‘6’. It is the 3rd argument passed in a call to RegisterTaskDefinition()

Now, let’s see how can we achieve this programmatically using C#.NET.
The below code will create\update a task under a Root Folder “\”. You may choose to create under a sub-folder.

Steps to create a task under Root Folder:

    1. Instantiate a task service and connect
      ITaskService taskService = new TaskScheduler();
    2. Create a new task using task Service object. This requires calling “taskService.NewTask(0)”

      ITaskDefinition taskDefinition = taskService.NewTask(0);
    3. Configure a new Task – all desirable properties like – Name, Description, Triggers, Actions, Author etc.

      taskDefinition.RegistrationInfo.Description = "task Description Goes Here";
      taskDefinition.RegistrationInfo.Author = "task Author domainName\userName goes here";
      taskDefinition.Settings.Enabled = “true or false”;
      taskDefinition.Settings.Hidden = “true or false”;
      taskDefinition.Settings.Compatibility = _TASK_COMPATIBILITY.TASK_COMPATIBILITY_V2_1;if (“You want to set the execution time limit for Task Actions”)
      {
      TimeSpan timespan = TimeSpan.FromMinutes(“No of minutes goes here”);

      // this is the format needed by COM
      taskDefinition.Settings.ExecutionTimeLimit = XmlConvert.ToString(timespan);
      }

      if (“You want to allow the task to execute only when system is idle for so many minutes”)
      {
      taskDefinition.Settings.RunOnlyIfIdle = “true or false”;

      TimeSpan timespan = TimeSpan.FromMinutes(“Number of Minutes Goes Here”);

      // this is the format needed by COM
      taskDefinition.Settings.IdleSettings.IdleDuration = XmlConvert.ToString(timespan);
      }

    4. Configure triggers, if any

      ITriggerCollection triggers = taskDefinition.Triggers;
      ITrigger trigger = triggers.Create("type of Trigger goes here"); // _TASK_TRIGGER_TYPE2 enumeration
      trigger.Enabled = "true or false";
      trigger.StartBoundary = DateTime.Now.ToString(Constants.DateTimeFormatExpectedByCOM);
      if (“You want this trigger to expire after sometime”)
      {
      trigger.EndBoundary = DateTime.Now.EndTime.ToString(Constants.DateTimeFormatExpectedByCOM);
      }
    5. Configure Actions [atleast one]

      IActionCollection actions = taskDefinition.Actions;
      _TASK_ACTION_TYPE actionType = "type of action you want goes here";
      IAction action = actions.Create(actionType);
      switch (actionType)
      {
      case _TASK_ACTION_TYPE.TASK_ACTION_EXEC:
      IExecAction execAction = action as IExecAction;execAction.Path = “Path to Program To Run goes here”;
      execAction.Arguments = “Optional Arguments goes here when starting the above executable”;
      break;

      case _TASK_ACTION_TYPE.TASK_ACTION_SEND_EMAIL:
      IEmailAction mailAction = action as IEmailAction;

      mailAction.From = “Sender email address goes here”;
      mailAction.To = “Receiver email address goes here”;
      mailAction.Server = “SMTPServer address goes here”;
      mailAction.Subject = “email Subject goes here” ;
      mailAction.Body = “email MessageBody goes here”;

      break;

      case _TASK_ACTION_TYPE.TASK_ACTION_SHOW_MESSAGE:
      IShowMessageAction showAction = action as IShowMessageAction;

      showAction.Title = “Display Title goes here”;
      showAction.MessageBody = “Display Message goes here”;
      break;
      }

    6. Till this point, we have configured task settings, triggers, actions, conditions. Now we need to register this task definition under some folder, RootFolder – “\”, here

      // creating this task in the root Folder
      // Create SubFolder under RootFolder, if you require
      ITaskFolder rootFolder = taskService.GetFolder(@"\");
      // ‘6’ as argument means this task can be created or updated [“CreateOrUpdate” flag]
      // if Name id empty or null, System will create a task with name as GUID
      rootFolder.RegisterTaskDefinition(task.Name, definition, 6, null, null, _TASK_LOGON_TYPE.TASK_LOGON_NONE, null);

That’s all we need to do. If luck goes with you:), you won’t get errors [not like me]. Just kidding.
If you get a new error, contact me. I’ll try to find a cause and suggest you a resolution.

Possible errors and exceptions

  • Error Code :-2147216616,
    System.Runtime.InteropServices.COMException (0x80041318): (8,44):StartBoundary:26-01-2012 08:28:31

Cause: “ExecutionTimeLimit”/ “IdleDuration” are expected in some format by COM and not just simple ToString() conversion
Resolution: Use System.Xml.XmlConvert.ToString(). [Spent lot of time to get to this]

  • System.Runtime.InteropServices.COMException (0x80041319): (38,4):Actions:

Cause: This means tat atleast one action should be specified when registering a task definition for a new task.
Simply put, a task should define atleast one action
Resolution: Specify atleast one action – be it : To send an email or To execute a task or To display a message

  • System.Runtime.InteropServices.InvalidComObjectException was caught
    Message=COM object that has been separated from its underlying RCW cannot be used.
    Source=mscorlib
    StackTrace:
    at System.StubHelpers.StubHelpers.StubRegisterRCW(Object pThis, IntPtr pThread)
    at TaskScheduler.ITaskService.get_Connected()InnerException:

Cause:
You are trying to work on the Released TaskScheduler COM object
Resolution:
Create a new object of TaskScheduler , connect and carry on with your task operation

  • Error Code: -2147221163. Interface not registered while creating a task.

Yet to identify the real cause and resolution. [Noticed this when i share the same TaskScheduler instance and use it from diferent win forms]

References


Advertisements

About Sunil Singhal

A human being whose dreams are tied to a Horse that will never tire
This entry was posted in .NET, Technical and tagged , , , , , . Bookmark the permalink.

24 Responses to Task Scheduler in C#.Net

  1. Fahad Mirza says:

    Kindly specify how do we get the following details of Registered Task.
    1) Task Repetition Interval.
    2) Repetition Time.
    3) Task Security Options.

    Like

  2. Siva says:

    private static void ScheduleTaskMonitoring()
    {
    //throw new NotImplementedException();
    ITaskService taskService = new TaskScheduler.TaskScheduler();
    taskService.Connect();

    ITaskFolder rootfolder = taskService.GetFolder(@”\”);
    IRegisteredTaskCollection tasks = rootfolder.GetTasks(0);
    int m = tasks.Count;

    foreach (IRegisteredTask s in tasks)
    {
    IRegisteredTask l = s;
    string p = l.Name;
    if (p == “Adobe Acrobat Update Task”)
    {
    int q = l.LastTaskResult;
    }
    }
    System.Runtime.InteropServices.Marshal.ReleaseComObject(tasks);

    }

    Like

  3. Krishna says:

    Upload the source code, that would benefit us

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s