2011-09-12 152 views
104

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

我该如何去做这件事,以及我需要什么使用指令和参考,因为我在搜索互联网时找不到太多东西。

+1

每个你需要的是这里:http://msdn.microsoft.com/en-us/library/aa383614(v=vs.85).aspx。 API,有关如何以编程方式实现所需内容的示例和解释。 – kroonwijk

回答

171

您可以使用Task Scheduler Managed Wrapper

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"); 
     } 
    } 
} 

或者您可以使用native API或去Quartz.NET。详情请参阅this

+2

是的,你需要下载并引用Microsoft.Win32.TaskScheduler.dll。链接在答案中。 – Dmitry

+0

对不起,我以为我确实添加了参考,但由于某种原因,它不是。对不起,但确实很好。感谢您的帮助 – Boardy

+1

@Dmitry你如何开始一项任务?你需要使用Windows调度程序注册吗? – Haroon

17

这对我的作品 https://www.nuget.org/packages/ASquare.WindowsTaskScheduler/

这是很好的设计流利的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(); 
+1

有没有办法将这些信息存储到SQL服务器数据库中? – Fearcoder