And also tell me about "Run whether user is logged on or not" in detail. to avoid future hurdles to run the created task(details about username and password)
To create a task in taskscheduler with the setting: "run wether user is loggd on or not" use following code:
var taskDefinition = taskService.NewTask();
taskDefinition.RegistrationInfo.Author = WindowsIdentity.GetCurrent().Name;
taskDefinition.RegistrationInfo.Description = "Runs Application";
// TaskLogonType.S4U = run wether user is logged on or not
taskDefinition.Principal.LogonType = TaskLogonType.S4U;
var action = new ExecAction(path, arguments);
taskDefinition.Actions.Add(action);
taskService.RootFolder.RegisterTaskDefinition("NameOfApplication", taskDefinition);
Note: I dont work with a Trigger here. You can start the created task directly from code with following code:
//get task:
var task = taskService.RootFolder.GetTasks().Where(a => a.Name == "NameOfApplication").FirstOrDefault();
try
{
task.Run();
}
catch (Exception ex)
{
log.Error("Error starting task in TaskSheduler with message: " + ex.Message);
}
You can set the UserId to SYSTEM
and it will automatically set the option 'Run whether user is logged on or not'.
using (TaskService ts = new TaskService())
{
var newTask = ts.NewTask();
newTask.Principal.UserId = "SYSTEM";
newTask.Triggers.Add(new TimeTrigger(DateTime.Now));
newTask.Actions.Add(new ExecAction("notepad"));
ts.RootFolder.RegisterTaskDefinition("NewTask", newTask);
}
The program executing the above code must run as Administrator.
Found this solution posted in the comments here, http://taskscheduler.codeplex.com/wikipage?title=Examples
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With