Jitesh Byahut 10/15/2014 46751

Create Task Scheduler In C#

Here we are Creating Task Scheduler in windows in C#. We are creating tasks that run daily, weekly, repeated and once. Here we are learning how to create scheduler that run when user is logger on or not as well as scheduler that run with highest privileges. After that we will update the task scheduler and also delete task scheduler from windows. For creating task scheduler, we are using TaskScheduler.dll that can downloaded from here.

First of all add reference of TaskScheduler.dll in you project and add below namespace in your .cs page.

using Microsoft.Win32.TaskScheduler;

Create Task Scheduler that run only one time

Here we are creating a task scheduler that name is TaskName that run on 17th Aug 2014 at 4:30 PM.

// Run only one time

    private void CreateTaskRunOnce()

    {       

       using (TaskService ts = new TaskService())

       {

         TaskDefinition td = ts.NewTask();

         td.RegistrationInfo.Description = "My first task scheduler";

         td.Triggers.Add(new TimeTrigger(){StartBoundary=Convert.ToDateTime("17-08-2014 16:30:00")});

 

         td.Actions.Add(new ExecAction(@"C:/sample.exe", null, null));

         ts.RootFolder.RegisterTaskDefinition("TaskName", td);

       }       

    }

Example:

Demo

Create Task Scheduler that run repeate in every one hour

Here we are creating a task scheduler that name is TaskName that run on every one hour continuously.

// Run in every 1 hour

    private void CreateTaskRunRepeatly()

    {

        // Run daily

        using (TaskService ts = new TaskService())

        {

            TaskDefinition td = ts.NewTask();

            td.RegistrationInfo.Description = "My first task scheduler";

 

            TimeTrigger trigger = new TimeTrigger();

            trigger.StartBoundary = DateTime.Now;

            trigger.Repetition.Interval = TimeSpan.FromMinutes(60);

            td.Triggers.Add(trigger);

 

            td.Actions.Add(new ExecAction(@"C:/sample.exe", null, null));

            ts.RootFolder.RegisterTaskDefinition("TaskName", td);

        }

    }

Example:

Demo

Create Task Scheduler that run daily

Here we are creating a task scheduler that name is TaskName that run every day at 4:30 PM.

// Run daily

    private void CreateTaskRunDaily()

    {       

        using (TaskService ts = new TaskService())

        {

            TaskDefinition td = ts.NewTask();

            td.RegistrationInfo.Description = "My first task scheduler";

 

            DailyTrigger daily = new DailyTrigger();

            daily.StartBoundary = Convert.ToDateTime(DateTime.Today.ToShortDateString()+" 16:30:00");

            daily.DaysInterval = 1;

            td.Triggers.Add(daily);

 

            td.Actions.Add(new ExecAction(@"C:/sample.exe", null, null));

            ts.RootFolder.RegisterTaskDefinition("TaskName", td);

        }

    }

Example:

Demo

Create Task Scheduler that run weekly

Here we are creating a task scheduler that name is TaskName that run on every week of Monday and Tuesday at 4:30 PM.

// Run Weekly

    private void CreateTaskRunWeekly()

    {       

        using (TaskService ts = new TaskService())

        {

            TaskDefinition td = ts.NewTask();

            td.RegistrationInfo.Description = "My first task scheduler";

 

            WeeklyTrigger week = new WeeklyTrigger();

            week.StartBoundary = Convert.ToDateTime(DateTime.Today.ToShortDateString()+" 16:30:00");

            week.WeeksInterval = 1;

            week.DaysOfWeek =  Microsoft.Win32.TaskScheduler.DaysOfTheWeek.Monday |
                               Microsoft.Win32.TaskScheduler.
DaysOfTheWeek.Tuesday;

            td.Triggers.Add(week);

 

            td.Actions.Add(new ExecAction(@"C:/sample.exe", null, null));

            ts.RootFolder.RegisterTaskDefinition("TaskName", td);

        }       

    }

Example:

Demo

Create Task Scheduler that run whether user logged on or not

Here we are creating a task scheduler that name is TaskName that run whether user logged on or not.

//// Run Task whether user logged on or not

    private void RunUserLoggedOnOrNot()

    {

        using (TaskService ts = new TaskService())

        {

            TaskDefinition td = ts.NewTask();

            td.RegistrationInfo.Description = "My first task scheduler";

            // Run Task whether user logged on or not

            td.Principal.LogonType = TaskLogonType.S4U;

 

            TimeTrigger trigger = new TimeTrigger();

            trigger.StartBoundary = DateTime.Now;

            trigger.Repetition.Interval = TimeSpan.FromMinutes(180);

            td.Triggers.Add(trigger);

 

            td.Actions.Add(new ExecAction(@"C:\simple.exe", null, null));

            ts.RootFolder.RegisterTaskDefinition("TaskName", td);

        }

    }

Example:

Demo

Create Task Scheduler run with highest privileges

Sometimes our task scheduler is not running properly because that has not privilege, so we can create task scheduler that has highest privileges.

// Run in every 5 hours

    private void RunWithHighestPrivileges()

    {

        using (TaskService ts = new TaskService())

        {

            TaskDefinition td = ts.NewTask();

            td.RegistrationInfo.Description = "My first task scheduler";

            // Run Task whether user logged on or not

            td.Principal.UserId=string.Concat(Environment.UserDomainName,"\\", Environment.UserName);

            td.Principal.LogonType = TaskLogonType.S4U;

            // Run as Administrator

            td.Principal.RunLevel = TaskRunLevel.Highest;

 

            TimeTrigger trigger = new TimeTrigger();

            trigger.StartBoundary = DateTime.Now;

            trigger.Repetition.Interval = TimeSpan.FromHours(5);

            td.Triggers.Add(trigger);

 

            td.Actions.Add(new ExecAction(@"C:\simple.exe", null, null));

            ts.RootFolder.RegisterTaskDefinition("TaskName", td);

        }

    }

While creating task scheduler that run with highest privileges using above code, you may face Access denie exceptions. So, in that case, open your visual studio run as administrator.

Example:

Demo

Create Task Scheduler that pass parameters

If you targeting .exe file accepting any argument, then you can pass that argument while creating task scheduler.

td.Actions.Add(new ExecAction(@"C:/sample.exe", "UpdateType", null));

ts.RootFolder.RegisterTaskDefinition("TaskName", td);

Example:

Demo

Create Task Scheduler that run multiple instances

you can create task scheduler that run multiple instances.

td.Settings.MultipleInstances = TaskInstancesPolicy.Parallel;

Delete Task Scheduler

You can delete you existing task from windows task scheduler list.

private void DeleteTask()

    {

        using (TaskService ts = new TaskService())

        {

            if (ts.GetTask("TaskName") != null)

            {

                ts.RootFolder.DeleteTask("TaskName");

            }

        }

    }

Update Task Scheduler Trigger

You can update you task running mode. For example, I create a task that running every 2 hours but now, I want to run my task in every 4 hours, so here, I updating existing task,

private void UpdateTaskTrigger()

{

        using (TaskService ts = new TaskService())

        {

            Microsoft.Win32.TaskScheduler.Task task = ts.GetTask("TaskName");

            TaskDefinition td = task.Definition;

            foreach (Microsoft.Win32.TaskScheduler.Trigger trigger in task.Definition.Triggers)

            {

                trigger.StartBoundary = DateTime.Now;

                trigger.Repetition.Interval = TimeSpan.FromHours(Convert.ToInt16(4));

            }

            ts.RootFolder.RegisterTaskDefinition("TaskName", td);

        }

}

Update Task Scheduler and add new trigger

In some cases, you can to run your same task in different-different running mode, so you can add numbers of trigger on you existing task or while creating. Here we are adding a new trigger on existing task in windows scheduler.

// Add multiple instances

    private void UpdateTaskAddNewTrigger()

    {

        using (TaskService ts = new TaskService())

        {

            Microsoft.Win32.TaskScheduler.Task task = ts.GetTask("TaskName");

            TaskDefinition td = task.Definition;

 

            TimeTrigger trigger = new TimeTrigger();

            trigger.StartBoundary = DateTime.Now;

            trigger.Repetition.Interval = TimeSpan.FromHours(3);

 

            td.Triggers.Add(trigger);

            ts.RootFolder.RegisterTaskDefinition("TaskName", td);

        }

    }

Example:

Demo


Please give your feedback for improving this page