创建计划任务

Boa*_*rdy 142 c# wpf scheduled-tasks

我正在开发一个C#WPF项目.我需要允许用户创建计划任务并将其添加到Windows任务计划程序.

我怎么能去做这个以及我需要什么使用指令和参考,因为我在搜索互联网时找不到多少.

Dmi*_*try 207

您可以使用任务计划程序托管包装器:

using System;
using Microsoft.Win32.TaskScheduler;

class Program
{
   static void Main(string[] args)
   {
      // Get the service on the local machine
      using (TaskService ts = new TaskService())
      {
         // Create a new task definition and assign properties
         TaskDefinition td = ts.NewTask();
         td.RegistrationInfo.Description = "Does something";

         // Create a trigger that will fire the task at this time every other day
         td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });

         // Create an action that will launch Notepad whenever the trigger fires
         td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));

         // Register the task in the root folder
         ts.RootFolder.RegisterTaskDefinition(@"Test", td);

         // Remove the task we just created
         ts.RootFolder.DeleteTask("Test");
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用本机 API或Quartz.NET.请参阅了解详情.

  • 是的,您需要下载并引用Microsoft.Win32.TaskScheduler.dll.链接在答案中. (2认同)
  • 我看到引用是针对win32的,如果我的服务器是64位怎么办? (2认同)
  • 由于CodePlex将在几个月后关闭,请注意任务计划程序托管包装器的NuGet页面,网址为https://www.nuget.org/packages/TaskScheduler/. (2认同)

小智 29

这对我 有用https://www.nuget.org/packages/ASquare.WindowsTaskScheduler/

它设计精美的Fluent API.

//This will create Daily trigger to run every 10 minutes for a duration of 18 hours
SchedulerResponse response = WindowTaskScheduler
    .Configure()
    .CreateTask("TaskName", "C:\\Test.bat")
    .RunDaily()
    .RunEveryXMinutes(10)
    .RunDurationFor(new TimeSpan(18, 0, 0))
    .SetStartDate(new DateTime(2015, 8, 8))
    .SetStartTime(new TimeSpan(8, 0, 0))
    .Execute();
Run Code Online (Sandbox Code Playgroud)