通过 C# 在任务计划程序中设置用户帐户

Set the user accounts in Task Scheduler through C#

我正在尝试使用我的 C# 程序在任务计划程序中设置以下选项。

1. In settings tab of Task scheduler, check the box "If the task fails, restart every 1 minute"
2. In General tab of Task scheduler, under security options, set it to "BigDataService" for "When running the task, use the following user account" and provide its password.

我当前的代码如下所示:

 using (TaskService ts = new TaskService())
 {
    TaskDefinition td = ts.NewTask();
    TimeTrigger trigger = new TimeTrigger();
    var startTime = TimeSpan.Parse(section1["ScheduledTime"]);
    trigger.StartBoundary = DateTime.Today + startTime;
    trigger.Repetition.Interval = TimeSpan.FromDays(1);
    trigger.StartBoundary = DateTime.Now;
    td.Principal.RunLevel = TaskRunLevel.Highest;
    trigger.Id = "Data";
    trigger.Repetition.Interval = TimeSpan.FromDays(1);
    td.Triggers.Add(trigger);
    td.Actions.Add(new ExecAction(@"DataUpload.exe", argument, null));
    var foldername = ts.GetFolder(@"\Bigdata");
    Console.WriteLine(foldername.Path);
    foldername.RegisterTaskDefinition(section1["JobName"], td);
}

New Cod(与 RegisterTaskDefinition 一起工作正常,但是当我添加 RepetitionInterval 行时,任务不会在 BigData 文件夹中创建。

using (TaskService ts = new TaskService())
 {
    TaskDefinition td = ts.NewTask();
    TimeTrigger trigger = new TimeTrigger();
    var startTime = TimeSpan.Parse(section1["ScheduledTime"]);
    trigger.StartBoundary = DateTime.Today + startTime;
    trigger.Repetition.Interval = TimeSpan.FromDays(1);
    trigger.StartBoundary = DateTime.Now;
    td.Principal.RunLevel = TaskRunLevel.Highest;
    trigger.Id = "Data";
    trigger.Repetition.Interval = TimeSpan.FromDays(1);
    td.Triggers.Add(trigger);
    td.Actions.Add(new ExecAction(@"DataUpload.exe", argument, null));
    var foldername = ts.GetFolder(@"\Bigdata");
    Console.WriteLine(foldername.Path);   
    foldername.RegisterTaskDefinition(section1["JobName"], td, TaskCreation.CreateOrUpdate,"Bigdataservice", "password");
}

要将重启间隔设置为 1 分钟:

td.Settings.RestartInterval = TimeSpan.FromMinutes(1);

设置登录:

td.Principal.LogonType = TaskLogonType.Group;
// Pass the credentials when you register the task
foldername.RegisterTaskDefinition(section1["JobName"], td,
    TaskCreation.CreateOrUpdate, "DOMAIN\USERNAME", "Pas$w0rD");