2011-09-12 13 views
104

Actualmente estoy trabajando en un proyecto C# WPF. Necesito permitir que el usuario cree y agregue una tarea programada al Programador de tareas de Windows.Creación de tareas programadas

¿Cómo puedo hacer esto y qué uso de directivas y referencias necesito ya que no encuentro mucho cuando busco en Internet.

+1

Cada lo que necesita es aquí: http://msdn.microsoft.com/en-us/library/aa383614(v=vs.85).aspx. API, ejemplos y explicaciones sobre cómo lograr lo que necesita programáticamente. – kroonwijk

Respuesta

171

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

Alternativamente, puede utilizar la API native o ir a Quartz.NET. Ver this para más detalles.

+2

Sí, debe descargar y hacer referencia a Microsoft.Win32.TaskScheduler.dll. El enlace está en la respuesta. – Dmitry

+0

Sí, lo siento, pensé que sí agregué la referencia, pero por alguna razón no fue así. Lo siento, pero funciona muy bien. Gracias por su ayuda – Boardy

+1

@Dmitry ¿cómo se inicia una tarea? ¿Necesita registrarlo con el programador de Windows o algo así? – Haroon

17

Esto funciona para mí https://www.nuget.org/packages/ASquare.WindowsTaskScheduler/

Se API Fluido muy bien diseñado.

//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

¿Hay alguna manera de almacenar esta información en una base de datos del servidor SQL? – Fearcoder

Cuestiones relacionadas