pavanarya

Let us share the knowledge

Scheduling a Task From c#

with 5 comments

Hi,
In this post i am working on how to schedule a task in windows XP using c#.
So in order to deal with Microsoft’s Scheduled Tasks from c#, i am making use of a dll that was written in c#.
Download the dll from

http://taskscheduler.codeplex.com/SourceControl/list/changesets

Click on download and then accept the terms.

After downloading the source code, unzip the downloaded file and we will have a dll and an xml file.

Now create an empty library project. Now add the reference Microsoft.Win32.TaskScheduler.dll that is downloaded to our project.
So now we are all set for creating and running scheduled tasks from our c# code.

To get the list of Tasks defined in the system.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32.TaskScheduler;
namespace TaskManager
{
    class Program
    {
        static void Main(string[] args)
        {
            using (TaskService ts = new TaskService())
            {
         //Gets List Of Tasks in a folder. For Root Folder use backslash
                TaskFolder taskFolder = ts.GetFolder(@"\");
                TaskCollection col = taskFolder.Tasks;
                foreach (Task t in col)
                {
                   string taskName= t.Name;
                   DateTime lastRuntime = t.LastRunTime;
                   DateTime nextRunTime = t.NextRunTime;
                   t.Run(null);
                   TaskDefinition taskDef = t.Definition;
                   ActionCollection actionCol = taskDef.Actions;
                    
                }
             }
         }
     }
}

For performing any type of operation TaskService class is the main class.
TaskFolder class contains the tasks already defined. There is a property called “Tasks” that returns the collection of tasks that is it returns all the tasks present in the Folder.

So each task in the TaskCollection contains a number of property that provide basic info about the task.
The property Name defines the task name, LastRunTime, NextRunTime provides the info about the last run and next run time.

If the task is not running presently then we can run that task using Run(param string[]parameters) and if we dont have any parameters then we can pass null.

There is a property “Definition” of Task class which return an object of class TaskDefinition. TaskDefinition class contains all the information about the user who added this task, the executable file that is executed with this task , the time intervals in which this task is executed.

Code to get the Executable info and to run the the stopped task:

using (TaskService ts = new TaskService())
 {
    //Gets List Of Tasks in a folder. For Root Folder use backslash
  TaskFolder taskFolder = ts.GetFolder(@"\");
   TaskCollection col = taskFolder.Tasks;
   foreach (Task t in col)
    {
    t.Run(null);//To run a particular task that is stopped right now.
   TaskDefinition taskDef = t.Definition;
   ActionCollection actionCol = taskDef.Actions;
   string pathOfExe=actionCol .toString();//returns the exe path.
     }
}

To Get the details of the user who added this task:

 using (TaskService ts = new TaskService())
            {
         //Gets List Of Tasks in a folder. For Root Folder use backslash
                TaskFolder taskFolder = ts.GetFolder(@"\");
                TaskCollection col = taskFolder.Tasks;
                foreach (Task t in col)
                {
                    TaskDefinition taskDef = t.Definition;
//To return userid
                    String userid=taskDef.Principal.UserId;
                }
            }

To Create a new Task in Scheduled Tasks

As already mentioned TaskService is the root class to work on scheduled tasks.
After TaskService class, TaskDefinition class is the main class which contains all the info about the triggers at which this task should be executed. Details of the user who added this task. The path of the file that needs to be executed when this task is running.

So in order to create a new task we should follow below steps.

step1: Create an object for TaskService class

step2: Create an object for TaskDefinition class by using the function NewTask() of the class TaskService. TaskDefinition contains entire definition of a task.

Step3: To TaskDefinition class inturn contains number of objects and each type of object gives specific details about the task.

step4: The TaskRegistrationInfo of the task is present in the class TaskRegistrationInfo . This class contains number of properties like author,description

step5:Create a trigger that will fire at the time specified. trigger Class is an abstract class.There are number of properties associated with Trigger class like startBoundary that specifies the time at which the trigger should be started.

step6:ExecAction class is used to specify the information related to the exe that should be executed when a trigger is fired.

step7: at last we should register the task created using RegisterTaskDefinition which accepts the path and the TaskDefinition class which contains all the details of the Task to register.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32.TaskScheduler;
namespace TaskManager
{
    class Program
    {
        static void Main(string[] args)
        {
            using (TaskService ts = new TaskService())
            {
// Create a new task definition and assign properties
                TaskDefinition td = ts.NewTask();
                td.RegistrationInfo.Description = "Open Notepad";
// Create a trigger that will fire the task now
                Trigger tg = Trigger.CreateTrigger(TaskTriggerType.Time);
                tg.StartBoundary = DateTime.Now;
                td.Triggers.Add(tg);
                // Create an action that will launch Notepad whenever the trigger fires
                td.Actions.Add(new ExecAction("notepad.exe", null, null));
                // Register the task in the root folder
                ts.RootFolder.RegisterTaskDefinition(@"Test", td);
            }
        }
    }
}

To Delete a task or add a new folder to root folder:

TaskService.RootFolder provides access to root folder where scheduled tasks are stored. Now we can delete tasks present in that using the function DeleteTasks(taskname).
There are some functions called CreateFolder,DeleteFolder but they are not supported in XP.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32.TaskScheduler;
namespace TaskManager
{
    class Program
    {
        static void Main(string[] args)
        {
            using (TaskService ts = new TaskService())
            {
                ts.RootFolder.DeleteTask("Test");
               // ts.RootFolder.CreateFolder("subFolder");
            }
        }
    }
}

So Task scheduling helps us to manipulate the tasks present in a different machine, to track the details of the running tasks or tasks that are currently not executing.

Thanks,
Pavan

About these ads

Written by pavanarya

January 8, 2012 at 11:38 pm

Posted in Asp.net

Tagged with ,

5 Responses

Subscribe to comments with RSS.

  1. Your style is so unique compared to many other people. Thank you for publishing when you have the opportunity,Guess I will just make this bookmarked.2

    Leopoldo Galyon

    January 10, 2012 at 2:51 pm

  2. helpful knowledge provided. ;)

    Muhammad Idrees

    March 7, 2012 at 4:06 pm

  3. This snipped code work in Windows2000

    Favio

    July 25, 2012 at 1:10 am

  4. Hello,
    I want a make a schedule of weekly twice as per to user demand, i;e the user will choose on which days he/she want to set the schedule from the 7 days of the week.And the user also change the schedule at any time and will schedule to any day of the week.
    Thank You
    Awaiting for your reply..!

    Gouri Shankar Chhotray

    October 27, 2012 at 5:07 pm

  5. The Scheduler WinForms Control is a lightweight UI component and support of customizing the Scheduler Control to create demand scheduling UI application.

    Lawrence

    September 4, 2013 at 2:13 pm


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

Follow

Get every new post delivered to your Inbox.

Join 67 other followers

%d bloggers like this: