web-dev-qa-db-fra.com

Création de tâches planifiées

Je travaille sur un projet C # WPF. Je dois permettre à l'utilisateur de créer et d'ajouter une tâche planifiée au planificateur de tâches Windows.

Comment puis-je m'y prendre et de quoi ai-je besoin à l'aide de directives et de références, car je ne trouve pas grand chose lorsque je cherche sur Internet.

139
Boardy

Vous pouvez utiliser wrapper managé du planificateur de tâches :

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

Sinon, vous pouvez utiliser l'API native ou opter pour Quartz.NET . Voir this pour plus de détails.

202
Dmitry

Cela fonctionne pour moi https://www.nuget.org/packages/ASquare.WindowsTaskScheduler/

Il est bien conçu API Fluent.

//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();
29
Uday Reddy