Whenever you create a Windows task scheduler basically you concern in two important thing
1.) Create a action that you want to perform.
2.) create the trigger of time interval and occureance to get that action execute.
In order to create a Windows task scheduler through code we shall follow the same pattern.
1.) Connect to Task Service.
2.) Create New task and setup the setting for that task.
3.) Create Trigger
4.) Create Action
5.) Register Task.
Implementation Steps.
The dll which help us achieve this is C:\Windows\System32\taskschd.dll. When you add this dll as reference it showed up as reference name "TaskScheduler". After adding this reference you just need to follow some steps in order to have that task setup and running. So the simplest task i am going to setup in open Notepad once at specific interval. So step to implement are.
1.) Connect to Task Service
ITaskService taskService = new TaskScheduler.TaskScheduler();
taskService.Connect();
2.) Create New task and setup the setting for that task.
ITaskDefinition taskDefinition = taskService.NewTask(0);
taskDefinition.Settings.MultipleInstances = _TASK_INSTANCES_POLICY.TASK_INSTANCES_IGNORE_NEW;
taskDefinition.RegistrationInfo.Description = "Testing the creation of a scheduled task via VB .NET";
taskDefinition.Principal.LogonType = _TASK_LOGON_TYPE.TASK_LOGON_GROUP;
taskDefinition.Settings.Hidden = false;
3.) Create Trigger
ITimeTrigger taskTrigger = (ITimeTrigger)taskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME);
taskTrigger.StartBoundary = DateTime.Now.AddMinutes(1).ToString("yyyy-MM-ddTHH:mm:ss" + TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).ToString().Substring(0, 6));
4.) Create Action
IExecAction taskAction = (IExecAction)taskDefinition.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
taskAction.Path = "C:\\windows\\notepad.exe";
taskAction.Arguments = "";
taskAction.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
5.) Register Task.
const string taskName = "Simple windows scheduled task";
ITaskFolder rootFolder = taskService.GetFolder("\\Test");
rootFolder.RegisterTaskDefinition(taskName, taskDefinition, Convert.ToInt32(_TASK_CREATION.TASK_CREATE_OR_UPDATE), "Administrator", "admin@123", _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN_OR_PASSWORD);
SO add the dll and combine the code from step 1 to 5 in single console application and run it you will have one task which run the notpad after 1 minute from now.
I know i am very brief but as a developer i thing a good developer need good direction and he can find the destination itself. and i spend my one full day in order to have configure everything.
Happy Coding!!!!