运行 使用 C# 的计划任务
Run Scheduled Task with C#
我创建了一个简单的任务。它在每个用户登录时启动。我还想在创建后立即启动它 -> 执行 Task Scheduler GUI 中的 "Run" 操作。我知道我可以启动一个新进程,并以这种方式执行操作目标。是否也可以仅使用 TaskService
对象来完成?这是示例代码:
using (TaskService ts = new TaskService()) {
// Create a new task definition and assign properties
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Author = "Me";
td.Principal.RunLevel = TaskRunLevel.Highest;
td.RegistrationInfo.Description = "Starts Updater";
td.Settings.DisallowStartIfOnBatteries = false;
td.Settings.Enabled = true;
td.Settings.ExecutionTimeLimit = TimeSpan.Zero;
td.Settings.Hidden = false;
td.Settings.IdleSettings.RestartOnIdle = false;
td.Settings.IdleSettings.StopOnIdleEnd = false;
td.Settings.Priority = System.Diagnostics.ProcessPriorityClass.High;
td.Settings.RunOnlyIfIdle = false;
td.Settings.RunOnlyIfNetworkAvailable = false;
td.Settings.StopIfGoingOnBatteries = false;
// Create a trigger that will fire the task at this time every other day
td.Triggers.Add(new LogonTrigger());
var fileName = Path.Combine(Environment.GetFolderPath("path_updater.exe");
// Create an action that will launch Notepad whenever the trigger fires
td.Actions.Add(new ExecAction(fileName, null, null));
// Register the task in the root folder
ts.RootFolder.RegisterTaskDefinition(@"Updater", td);
}
就像您右键单击创建的任务并在 TaskScheduler GUI 上单击 运行
这样注册任务后就可以使用Task.Run()
.
.
ts.RootFolder.RegisterTaskDefinition(@"Updater", td);
var runCreatedTask = ts.FindTask("Updater").Run(); //Runs the registered task immediately
我创建了一个简单的任务。它在每个用户登录时启动。我还想在创建后立即启动它 -> 执行 Task Scheduler GUI 中的 "Run" 操作。我知道我可以启动一个新进程,并以这种方式执行操作目标。是否也可以仅使用 TaskService
对象来完成?这是示例代码:
using (TaskService ts = new TaskService()) {
// Create a new task definition and assign properties
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Author = "Me";
td.Principal.RunLevel = TaskRunLevel.Highest;
td.RegistrationInfo.Description = "Starts Updater";
td.Settings.DisallowStartIfOnBatteries = false;
td.Settings.Enabled = true;
td.Settings.ExecutionTimeLimit = TimeSpan.Zero;
td.Settings.Hidden = false;
td.Settings.IdleSettings.RestartOnIdle = false;
td.Settings.IdleSettings.StopOnIdleEnd = false;
td.Settings.Priority = System.Diagnostics.ProcessPriorityClass.High;
td.Settings.RunOnlyIfIdle = false;
td.Settings.RunOnlyIfNetworkAvailable = false;
td.Settings.StopIfGoingOnBatteries = false;
// Create a trigger that will fire the task at this time every other day
td.Triggers.Add(new LogonTrigger());
var fileName = Path.Combine(Environment.GetFolderPath("path_updater.exe");
// Create an action that will launch Notepad whenever the trigger fires
td.Actions.Add(new ExecAction(fileName, null, null));
// Register the task in the root folder
ts.RootFolder.RegisterTaskDefinition(@"Updater", td);
}
就像您右键单击创建的任务并在 TaskScheduler GUI 上单击 运行
这样注册任务后就可以使用Task.Run()
.
.
ts.RootFolder.RegisterTaskDefinition(@"Updater", td);
var runCreatedTask = ts.FindTask("Updater").Run(); //Runs the registered task immediately