Reputation: 272
I've created a C# program which creates remote jobs, and then spawns follow-up processes every 5 minutes to check on the status of the remote job. This is accomplished with a mother task in task scheduler which creates child tasks.
It all runs fine as me on my local machine; However, in production I have 2 issues:
Here is the code I use to create the task from the mother task:
{
TaskService ts = new TaskService();
TaskDefinition td = ts.NewTask();
//td.Settings.RunOnlyIfLoggedOn = false;
td.Principal.LogonType = TaskLogonType.S4U;
td.Settings.AllowDemandStart = true;
td.Settings.MultipleInstances = TaskInstancesPolicy.IgnoreNew;
td.Principal.RunLevel = TaskRunLevel.Highest;
td.RegistrationInfo.Description = taskDescription;
td.Triggers.Add(new TimeTrigger(DateTime.Now.AddMinutes(5)));
td.Actions.Add(action, arguments);
Microsoft.Win32.TaskScheduler.Task th = ts.RootFolder.RegisterTaskDefinition(taskName, td);
}
A few additional notes: - The mother task is set to run regardless if the user is logged on, and run with highest privileges. - The child task always appears like this:
I have seen several similar posts, but they all are missing the aspect of creating a task from a task.
Thanks!
Upvotes: 5
Views: 3528
Reputation: 6968
This will run the Task with the highest privileges and if the user is logged on or not:
// Get the service on the local machine
using (TaskService ts = new TaskService())
{
// Create a new task definition and assign properties
TaskDefinition td = ts.NewTask();
// Logged on or not with highest privileges
td.Principal.LogonType = TaskLogonType.S4U;
td.Principal.RunLevel = TaskRunLevel.Highest;
// Simple task to kill an application
td.RegistrationInfo.Description = $"Kill application {key}";
td.Triggers.Add(new TimeTrigger(DateTime.Now.AddMinutes(1))
{
Repetition = new RepetitionPattern(TimeSpan.FromMinutes(5), TimeSpan.Zero)
});
td.Actions.Add(new ExecAction("taskkill", $"/F /IM {key}.exe", null));
ts.RootFolder.RegisterTaskDefinition($"Kill {key}", td);
}
Upvotes: 1