Partilhar via


Code to create a task in Windows Task Scheduler

 

    1: TaskSchedulerClass scheduler = new TaskSchedulerClass();
    2: scheduler.Connect(null, null, null, null);
    3:  
    4: ITaskDefinition task = scheduler.NewTask(0);
    5: task.RegistrationInfo.Author = "MS PFE";
    6: task.RegistrationInfo.Description = ".....";
    7:  
    8: IDailyTrigger trigger = (IDailyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY);
    9: trigger.Id = "TaskName-Trigger";
   10: trigger.DaysInterval = 1;
   11: trigger.StartBoundary = "2012-06-01T23:55:00";
   12: trigger.EndBoundary = "2020-06-01T23:55:00";
   13:  
   14: IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
   15: action.Id = "GetContentDBDetails-Action";
   16: action.Path = @assemblypath;
   17: action.WorkingDirectory = @"C:\Program Files\Microsoft\..."; //generally the folder in which assembly is placed
   18:  
   19: ITaskFolder folder = scheduler.GetFolder("\\");
   20: IRegisteredTask regTask = folder.RegisterTaskDefinition(
   21:     "TaskName",
   22:     task,
   23:     (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE,
   24:     Environment.UserName, //System.Security.Principal.WindowsIdentity.GetCurrent().Name,
   25:     null, 
   26:     _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, "");