Quantcast
Channel: Task Scheduler Managed Wrapper
Viewing all 2206 articles
Browse latest View live

New Post: I want to create a schedule that will run every 1 hour in a day.

$
0
0
Assuming the task begins triggering immediately, runs indefinitely and executes a program:
DailyTrigger dt = new DailyTrigger();
dt.Repetition.Duration = TimeSpan.FromHours(23);
dt.Repetition.Interval = TimeSpan.FromHours(1);
new TaskService().AddTask(taskName, dt, new ExecAction("notepad.exe", "c:\\test.log", null));

New Post: Task history filter or sort

$
0
0
Is there a way to filter a TaskEventLog, or to loop through it in descending date order? Some tasks have a huge number of history entries, so it takes a long time to go through them all. In most cases, we're only interested in entries from the last week or to.

New Post: Task history filter or sort

$
0
0
The TaskEventLog constructor allows you specify a start time, as task name and a machine name as filters.

For even fewer entries, you can also use the CorrelatedTaskEventLog which collects all events for a single trigger into a single record. It has a similar constructor. See the HomePanel.cs file in the TestTaskService project for an example of how to use it in a BackgroundWorkerThread.

New Comment on "Examples"

$
0
0
There is so much here I'm having trouble finding the simple things. How do I schedule something to run every 10 minutes all day every day?

New Post: I want to create a schedule that will run every 1 hour in a day.

$
0
0
Thanks, It worked.

I have another query. In task scheduler General Tab - I want to select radio button "Run weather user is logged on or not".
I am getting error by trying following code:

CODE:
TaskDefinition td = ts.NewTask();
td.Settings.RunOnlyIfLoggedOn = false;
ERROR:
NotV2SupportedException' was unhandled. An unhandled exception of type 'Microsoft.Win32.TaskScheduler.NotV2SupportedException' occurred in          Microsoft.Win32.TaskScheduler.dll

New Post: I want to create a schedule that will run every 1 hour in a day.

$
0
0
Yes. That setting is reserved for systems after XP. You must be on an XP or Server 2003 system.

New Comment on "Examples"

$
0
0
>>Chizl: You can find an exampe at http://taskscheduler.codeplex.com/discussions/433076 for something very similar. You will use the DailyTrigger with a repetition interval and duration defined.

New Post: I want to create a schedule that will run every 1 hour in a day.

$
0
0
No, I am trying to run the program on Win 8 operating system.

New Post: Task history filter or sort

$
0
0
I don't see an option to include a start time, though that sound like exactly what I need. I see only two overloads, one to specify the TaskPath, and one to specify MachineName and TaskPath. Is the date option in a recent version?

New Post: I want to create a schedule that will run every 1 hour in a day.

$
0
0
I was incorrect. That setting only works on XP and earlier. To do what you want on Vista and later, int the RegisterTaskDefinition method you need to supply a password and use the TaskLogonType.Password or InteractiveTokenOrPassword or you will need to use a service account (like System or Local Service) and the TaskLogonType.ServiceAccount or you can supply a normal account, use the TaskLogonType.S4U, and not access either the network or encrypted files.

Updated Wiki: Examples

$
0
0
Below are some examples of how to use most of the functions of the library:

You can also go to these pages for more sample code:

Connecting to a remote server
// Connect to the computer "REMOTE" using credentials
TaskService ts = new TaskService("\\REMOTE", "myusername", "MYDOMAIN", "mypassword");

Using the editor
// Get the service on the local machineusing (TaskService ts = new TaskService())
{
   // Create a new taskconststring taskName = "Test";
   Task t = ts.AddTask(taskName, 
      new TimeTrigger() { StartBoundary = DateTime.Now + TimeSpan.FromHours(1), Enabled = false },
      new ExecAction("notepad.exe", "c:\\test.log", "C:\\"));

   // Edit task and re-register if user clicks Ok
   TaskEditDialog editorForm = new TaskEditDialog();
   editorForm.Editable = true;
   editorForm.RegisterTaskOnAccept = true;
   editorForm.Initialize(t);
   // ** The four lines above can be replaced by using the full constructor -- TaskEditDialog(t, true, true)
   editorForm.ShowDialog();

   // Remove the task we just created
   ts.RootFolder.DeleteTask(taskName);
}

Simple example
// Get the service on the local machineusing (TaskService ts = new TaskService())
{
   // Create a new task definition and assign properties
   TaskDefinition td = ts.NewTask();
   td.RegistrationInfo.Description = "Does something";
   td.Principal.LogonType = TaskLogonType.InteractiveToken;

   // Add a trigger that will fire the task at this time every other day
   DailyTrigger dt = (DailyTrigger)td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });
   dt.Repetition.Duration = TimeSpan.FromHours(4);
   dt.Repetition.Interval = TimeSpan.FromHours(1);

   // Add a trigger that will fire every week on Friday
   td.Triggers.Add(new WeeklyTrigger { StartBoundary = DateTime.Today + TimeSpan.FromHours(2), DaysOfWeek = DaysOfTheWeek.Friday });

   // Add 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 folderconststring taskName = "Test";
   ts.RootFolder.RegisterTaskDefinition(taskName, td);

   // Retrieve the task, change the trigger and re-register it
   Task t = ts.GetTask(taskName);
   td = t.Definition;
   td.Triggers[0].StartBoundary = DateTime.Today + TimeSpan.FromDays(7);
   ts.RootFolder.RegisterTaskDefinition(taskName, td);

   // Remove the task we just created
   ts.RootFolder.DeleteTask(taskName);
}

Enumerate all tasks
void EnumAllTasks()
{
   using (TaskService ts = new TaskService())
      EnumFolderTasks(ts.RootFolder);
}

void EnumFolderTasks(TaskFolder fld)
{
   foreach (Task task in fld.Tasks)
      ActOnTask(task);
   foreach (TaskFolder sfld in fld.SubFolders)
      EnumFolderTasks(sfld);
}

void ActOnTask(Task t)
{
   // Do something interesting here
}

Complex example
string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
bool preWin7 = true;

// Get the service on the local machineusing (TaskService ts = new TaskService())
{
   // Display version and server state
   Version ver = ts.HighestSupportedVersion;
   bool newVer = (ver >= new Version(1, 2));
   Console.WriteLine("Highest version: " + ver);
   Console.WriteLine("Server: {0} ({1})", ts.TargetServer, ts.Connected ? "Connected" : "Disconnected");

   // Output all of the running tasks
   Console.WriteLine("Running tasks:");
   foreach (RunningTask rt in ts.GetRunningTasks(true))
   {
      if (rt != null)
      {
         Console.WriteLine("+ {0}, {1} ({2})", rt.Name, rt.Path, rt.State);
         if (ver.Minor > 0)
            Console.WriteLine("  Current Action: " + rt.CurrentAction);
      }
   }

   // Output all the tasks in the root folder with their triggers and actions
   TaskFolder tf = ts.RootFolder;
   Console.WriteLine("\nRoot folder tasks ({0}):", tf.Tasks.Count);
   foreach (Task t in tf.Tasks)
   {
      try
      {
         Console.WriteLine("+ {0}, {1} ({2})", t.Name, t.Definition.RegistrationInfo.Author, t.State);
         foreach (Trigger trg in t.Definition.Triggers)
            Console.WriteLine(" + {0}", trg);
         foreach (Action act in t.Definition.Actions)
            Console.WriteLine(" = {0}", act);
      }
      catch { }
   }

   // Output an enumeration of all folders under the root
   Console.WriteLine("\n***Checking folder enum***");
   TaskFolderCollection tfs = tf.SubFolders;
   if (tfs.Count > 0)
   {
      Console.WriteLine("\nSub folders:");
      try
      {
         foreach (TaskFolder sf in tfs)
            Console.WriteLine("+ {0}", sf.Path);
      }
      catch (Exception ex)
      {
         Console.WriteLine(ex.ToString());
      }
   }

   // Display information about the Microsoft folderif (newVer)
   {
      Console.WriteLine("\n***Checking folder retrieval***");
      try
      {
         TaskFolder sub = tf.SubFolders["Microsoft"];
         Console.WriteLine("\nSubfolder path: " + sub.Path);
      }
      catch (NotSupportedException) { }
      catch (Exception ex)
      {
         Console.WriteLine(ex.ToString());
      }
   }

   Console.WriteLine("\n***Checking task creation***");
   try
   {
      // Create a new task definition and assign properties
      TaskDefinition td = ts.NewTask();
      td.Data = "Your data";
      td.Principal.UserId = user;
      td.Principal.LogonType = TaskLogonType.InteractiveToken;
      td.RegistrationInfo.Author = "dahall";
      td.RegistrationInfo.Description = "Does something";
      td.RegistrationInfo.Documentation = "Don't pretend this is real.";
      td.Settings.DisallowStartIfOnBatteries = true;
      td.Settings.Enabled = false;
      td.Settings.ExecutionTimeLimit = TimeSpan.FromHours(2);
      td.Settings.Hidden = false;
      td.Settings.IdleSettings.IdleDuration = TimeSpan.FromMinutes(20);
      td.Settings.IdleSettings.RestartOnIdle = false;
      td.Settings.IdleSettings.StopOnIdleEnd = false;
      td.Settings.IdleSettings.WaitTimeout = TimeSpan.FromMinutes(10);
      td.Settings.Priority = System.Diagnostics.ProcessPriorityClass.Normal;
      td.Settings.RunOnlyIfIdle = false;
      td.Settings.RunOnlyIfNetworkAvailable = false;
      td.Settings.StopIfGoingOnBatteries = true;
      if (newVer)
      {
         td.Principal.RunLevel = TaskRunLevel.Highest; //.LUA;//td.RegistrationInfo.SecurityDescriptorSddlForm = "O:COG:CGD::(A;;RPWPCCDCLCSWRCWDWOGA;;;S-1-0-0)";
         td.RegistrationInfo.Source = "Test App";
         td.RegistrationInfo.URI = new Uri("test://app");
         td.RegistrationInfo.Version = new Version(0, 9);
         td.Settings.AllowDemandStart = true;
         td.Settings.AllowHardTerminate = true;
         td.Settings.Compatibility = TaskCompatibility.V2;
         td.Settings.DeleteExpiredTaskAfter = TimeSpan.FromMinutes(1);
         td.Settings.MultipleInstances = TaskInstancesPolicy.StopExisting;
         td.Settings.StartWhenAvailable = true;
         td.Settings.WakeToRun = false;
         td.Settings.RestartCount = 5;
         td.Settings.RestartInterval = TimeSpan.FromSeconds(100);
      }

      if (preWin7)
      {
         // Create a trigger that fires 5 minutes after the system is booted
         BootTrigger bTrigger = (BootTrigger)td.Triggers.Add(new BootTrigger { Enabled = false });
         if (newVer) bTrigger.Delay = TimeSpan.FromMinutes(5);
      }

      // Create a trigger that fires every other day randomly between 6:00 a.m. and 8:00 a.m.
      DailyTrigger dTrigger = (DailyTrigger)td.Triggers.Add(new DailyTrigger());
      dTrigger.StartBoundary = DateTime.Today + TimeSpan.FromHours(6);
      dTrigger.DaysInterval = 2;
      if (newVer) dTrigger.RandomDelay = TimeSpan.FromHours(2);

      if (newVer)
      {
         if (preWin7)
         {
            // Create a trigger that will fire on a system security event
            EventTrigger eTrigger = (EventTrigger)td.Triggers.Add(new EventTrigger());
            eTrigger.SetBasic("Security", "VSSAudit", 25);
            eTrigger.ValueQueries.Add("Name", "Value");
         }

         // Create a trigger that fires 5 minutes after this task is registered
         td.Triggers.Add(new RegistrationTrigger { Delay = TimeSpan.FromMinutes(5) });

         if (preWin7)
         {
            // Create triggers that fire after various system states are changed
            td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.ConsoleConnect, UserId = user });
            td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.ConsoleDisconnect });
            td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.RemoteConnect });
            td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.RemoteDisconnect });
            td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.SessionLock, UserId = user });
            td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.SessionUnlock });
         }
      }

      // Create a trigger that fires when the system is idle
      td.Triggers.Add(new IdleTrigger());

      // Create a trigger that fires 15 minutes after the current user logs on and then every 1000 seconds after that
      LogonTrigger lTrigger = (LogonTrigger)td.Triggers.Add(new LogonTrigger());
      if (newVer)
      {
         lTrigger.Delay = TimeSpan.FromMinutes(15);
         lTrigger.UserId = user;
         lTrigger.Repetition.Interval = TimeSpan.FromSeconds(1000);
      }

      // Create a trigger that fires on the 3rd, 6th, 10th, 18th, and last days of July and November and stops triggering 90 days from now
      MonthlyTrigger mTrigger = (MonthlyTrigger)td.Triggers.Add(new MonthlyTrigger());
      mTrigger.DaysOfMonth = newint[] { 3, 6, 10, 18 };
      mTrigger.MonthsOfYear = MonthsOfTheYear.July | MonthsOfTheYear.November;
      if (newVer) mTrigger.RunOnLastDayOfMonth = true;
      mTrigger.EndBoundary = DateTime.Today + TimeSpan.FromDays(90);

      // Create a trigger that fires every day of the first and last week of December and January
      MonthlyDOWTrigger mdTrigger = (MonthlyDOWTrigger)td.Triggers.Add(new MonthlyDOWTrigger());
      mdTrigger.DaysOfWeek = DaysOfTheWeek.AllDays;
      mdTrigger.MonthsOfYear = MonthsOfTheYear.January | MonthsOfTheYear.December;
      if (newVer) mdTrigger.RunOnLastWeekOfMonth = true;
      mdTrigger.WeeksOfMonth = WhichWeek.FirstWeek;

      // Create a trigger that fires 1 minute from now and then every 15 minutes for the next 7 days.
      TimeTrigger tTrigger = (TimeTrigger)td.Triggers.Add(new TimeTrigger());
      tTrigger.StartBoundary = DateTime.Now + TimeSpan.FromMinutes(1);
      tTrigger.EndBoundary = DateTime.Today + TimeSpan.FromDays(7);
      if (newVer) tTrigger.ExecutionTimeLimit = TimeSpan.FromSeconds(15);
      if (newVer) tTrigger.Id = "Time test";
      tTrigger.Repetition.Duration = TimeSpan.FromMinutes(20);
      tTrigger.Repetition.Interval = TimeSpan.FromMinutes(15);
      tTrigger.Repetition.StopAtDurationEnd = true;

      // Create a trigger that fires every third week on Monday
      WeeklyTrigger wTrigger = (WeeklyTrigger)td.Triggers.Add(new WeeklyTrigger());
      wTrigger.DaysOfWeek = DaysOfTheWeek.Monday;
      wTrigger.WeeksInterval = 3;

      // Create an action which opens a log file in notepad
      td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));
      if (newVer)
      {
         // Create an action which shows a message to the interactive user
         td.Actions.Add(new ShowMessageAction("Running Notepad", "Info"));
         // Create an action which sends an email
         td.Actions.Add(new EmailAction("Testing", "dahall@codeplex.com", "user@test.com", "You've got mail.", "mail.myisp.com"));
         // Create an action which loads a COM object and calls the ITaskHandler interface
         td.Actions.Add(new ComHandlerAction(new Guid("CE7D4428-8A77-4c5d-8A13-5CAB5D1EC734"), string.Empty));
      }

      // Register the task definition (saves it) in the security context of the interactive user
      tf.RegisterTaskDefinition("Test", td, TaskCreation.CreateOrUpdate, null, null, TaskLogonType.InteractiveToken, null);
   }
   catch (Exception ex)
   {
      Console.WriteLine(ex.ToString());
   }

   // Display information about the newly created task
   Task runningTask = tf.Tasks["Test"];
   Console.WriteLine("\nNew task will run at " + runningTask.NextRunTime);
   Console.WriteLine("\nNew task triggers:");
   for (int i = 0; i < runningTask.Definition.Triggers.Count; i++)
      Console.WriteLine("  {0}: {1}", i, runningTask.Definition.Triggers[i]);
   Console.WriteLine("\nNew task actions:");
   for (int i = 0; i < runningTask.Definition.Actions.Count; i++)
      Console.WriteLine("  {0}: {1}", i, runningTask.Definition.Actions[i]);

   // Remove the task we just created since this was just a test
   tf.DeleteTask("Test");
}

Task history example
Only works with release 1.6.2 or source code drop 66948 and later and requires the inclusion of the TaskSchedulerEditor assembly.
TaskEventLog log = new TaskEventLog(task.Path);
List<ListViewItem> c = new List<ListViewItem>(100);
foreach (TaskEvent item in log)
   c.Add(new ListViewItem(newstring[] { item.Level, item.TimeCreated.ToString(), item.EventId.ToString(),
      item.TaskCategory, item.OpCode, item.ActivityId.ToString() }));

New Post: Task history filter or sort

$
0
0
Yes. It was either 1.9.1 or 1.9.2.

Updated Wiki: Documentation

$
0
0
There is a help file included with the download that provides an overview of the various classes. The Microsoft MSDN documentation provides an excellent overview of the Task Scheduler along with details around security and permission, idle conditions, and trigger repetition.
  • The Examples Page shows some C# code that demonstrates almost every function of the library.
  • The Installation Page explains how to use this library in your own projects and includes a sample project.
The TaskService class represents the machine specific instance of the system task scheduler. It provides access to information about the service, access folders (2.0 only), and can quickly add or retrieve a task. If you only need to use the library for very intermitant periods, wrap the TaskService instantiation in a using statement to easily disconnect at the end of your use. However, if you plan on using the connection to the Task Scheduler repeatedly, use an assembly level field to store the TaskService instance as connecting and disconnecting is an expensive operation.

Tasks are accessed and can be enumerated through a TaskFolder. For systems supporting only the 1.0 library, there is only the root folder. The 2.0 library supports a hierarchal structure similar to a file system. The Tasks property exposes a TaskCollection instance which can enumerate tasks and provides an indexer which allows access to individual tasks by name. The TaskCollection class also has methods that allow for the creation/registration and deletion of tasks and subfolders by name.

A task is represented by a Task instance. The Task class provides information about tasks state and history and exposes the task's TaskDefinition through the Definition property.

A TaskDefinition exposes all of the properties of a task which allow you to define how and what will run when the task is triggered. A task must have at least one action and one trigger defined.

Each task has a list of triggers that determine when the task will be run. These are accessed through the Triggers property of a task definition which exposes a TriggerCollection instance. TriggerCollection provides an indexer which allows access to individual triggers by their position in the list. The TriggerCollection class also has methods that allow for the addition and removal of triggers. TriggerCollection implements the IList interface so you can also enumerate all tasks using the foreach construct.

The Trigger class is an abstract class that forms the foundation of the different types of triggers that can be specified for a task. There are 10 different specializations that provide different ways to specify the time a task will run. Not all specializations work with the 1.0 library. See the help file for details about each of the trigger classes. The Trigger Documentation has some examples of how to setup each kind of trigger.

The Action class is an abstract class that is the foundation for four different actions. On 1.0, only the ExecAction specialization is available. These actions determine what the service will do when a trigger is fired. The Action Documentation has some examples of how to setup each kind of action.

Below is a brief example of how to use the library from C#.

using System;
using Microsoft.Win32.TaskScheduler;

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

         // Add a trigger that will fire every other week on Monday and Saturday and// repeat every 10 minutes for the following 11 hours
         WeeklyTrigger wt = new WeeklyTrigger(DaysOfTheWeek.Monday | DaysOfTheWeek.Saturday, 2);
         wt.Repetition.Duration = TimeSpan.FromHours(11)
         wt.Repetition.Interval = TimeSpan.FromMinutes(10)
         td.Triggers.Add(wt)

         // 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);
      }
   }
}
Here's the same as above but in VB.NET

Imports Microsoft.Win32.TaskScheduler

Module Module1

    Sub Main()
        Using ts AsNew TaskService()
            ' Create a new task definition and assign propertiesDim td As TaskDefinition = ts.NewTask
            td.RegistrationInfo.Description = "Does something"' Add a trigger that will fire every other week on Monday and Saturday and' repeat every 10 minutes for the following 11 hoursDim wt AsNew WeeklyTrigger(DaysOfTheWeek.Monday Or DaysOfTheWeek.Saturday, 2)
            wt.Repetition.Duration = TimeSpan.FromHours(11)
            wt.Repetition.Interval = TimeSpan.FromMinutes(10)
            td.Triggers.Add(wt)

            ' Add an action (shorthand) that runs Notepad
            td.Actions.Add(New ExecAction("notepad.exe", "C:\Test.log"))

            ' Register the task in the root folder
            ts.RootFolder.RegisterTaskDefinition("Test", td)
        EndUsingEndSubEndModule
If you're really into shorthand code, here's almost the same functionality as the C# code above, but much shorter:

using System;
using Microsoft.Win32.TaskScheduler;

class Program
{
   staticvoid Main(string[] args)
   {
      new TaskService().AddTask("Test", new DailyTrigger { DaysInterval = 2 }, new ExecAction("notepad.exe", "c:\\test.log", null));
   }
}

Updated Wiki: Documentation

$
0
0
There is a help file included with the download that provides an overview of the various classes. The Microsoft MSDN documentation provides an excellent overview of the Task Scheduler along with details around security and permission, idle conditions, and trigger repetition.
  • The Examples Page shows some C# code that demonstrates almost every function of the library.
  • The Installation Page explains how to use this library in your own projects and includes a sample project.
The TaskService class represents the machine specific instance of the system task scheduler. It provides access to information about the service, access folders (2.0 only), and can quickly add or retrieve a task. If you only need to use the library for very intermitant periods, wrap the TaskService instantiation in a using statement to easily disconnect at the end of your use. However, if you plan on using the connection to the Task Scheduler repeatedly, use an assembly level field to store the TaskService instance as connecting and disconnecting is an expensive operation.

Tasks are accessed and can be enumerated through a TaskFolder. For systems supporting only the 1.0 library, there is only the root folder. The 2.0 library supports a hierarchal structure similar to a file system. The Tasks property exposes a TaskCollection instance which can enumerate tasks and provides an indexer which allows access to individual tasks by name. The TaskCollection class also has methods that allow for the creation/registration and deletion of tasks and subfolders by name.

A task is represented by a Task instance. The Task class provides information about tasks state and history and exposes the task's TaskDefinition through the Definition property.

A TaskDefinition exposes all of the properties of a task which allow you to define how and what will run when the task is triggered. A task must have at least one action and one trigger defined.

Each task has a list of triggers that determine when the task will be run. These are accessed through the Triggers property of a task definition which exposes a TriggerCollection instance. TriggerCollection provides an indexer which allows access to individual triggers by their position in the list. The TriggerCollection class also has methods that allow for the addition and removal of triggers. TriggerCollection implements the IList interface so you can also enumerate all tasks using the foreach construct.

The Trigger class is an abstract class that forms the foundation of the different types of triggers that can be specified for a task. There are 10 different specializations that provide different ways to specify the time a task will run. Not all specializations work with the 1.0 library. See the help file for details about each of the trigger classes. The Trigger Documentation has some examples of how to setup each kind of trigger.

The Action class is an abstract class that is the foundation for four different actions. On 1.0, only the ExecAction specialization is available. These actions determine what the service will do when a trigger is fired. The Action Documentation has some examples of how to setup each kind of action.

Below is a brief example of how to use the library from C#.

using System;
using Microsoft.Win32.TaskScheduler;

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

         // Add a trigger that, starting tomorrow, will fire every other week on Monday// and Saturday and repeat every 10 minutes for the following 11 hours
         WeeklyTrigger wt = new WeeklyTrigger();
         wt.StartBoundary = DateTime.Today.AddDays(1);
         wt.DaysOfWeek = DaysOfTheWeek.Monday | DaysOfTheWeek.Saturday;
         wt.WeeksInterval = 2;
         wt.Repetition.Duration = TimeSpan.FromHours(11);
         wt.Repetition.Interval = TimeSpan.FromMinutes(10);
         td.Triggers.Add(wt)

         // 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);
      }
   }
}
Here's the same as above but in VB.NET

Imports Microsoft.Win32.TaskScheduler

Module Module1

    Sub Main()
        Using ts AsNew TaskService()
            ' Create a new task definition and assign propertiesDim td As TaskDefinition = ts.NewTask
            td.RegistrationInfo.Description = "Does something"' Add a trigger that will, starting tomorrow, fire every other week on Monday' and Saturday and repeat every 10 minutes for the following 11 hoursDim wt AsNew WeeklyTrigger()
            wt.StartBoundary = DateTime.Today.AddDays(1)
            wt.DaysOfWeek = DaysOfTheWeek.Monday Or DaysOfTheWeek.Saturday
            wt.WeeksInterval = 2
            wt.Repetition.Duration = TimeSpan.FromHours(11)
            wt.Repetition.Interval = TimeSpan.FromMinutes(10)
            td.Triggers.Add(wt)

            ' Add an action (shorthand) that runs Notepad
            td.Actions.Add(New ExecAction("notepad.exe", "c:\test.log"))

            ' Register the task in the root folder
            ts.RootFolder.RegisterTaskDefinition("Test", td)
        EndUsingEndSubEndModule
If you're really into shorthand code, here's almost the same functionality as the C# code above, but much shorter:

using System;
using Microsoft.Win32.TaskScheduler;

class Program
{
   staticvoid Main(string[] args)
   {
      new TaskService().AddTask("Test", new DailyTrigger { DaysInterval = 2 }, new ExecAction("notepad.exe", "c:\\test.log", null));
   }
}

New Post: Small code improvement in Trigger.cs

$
0
0
After some tests, I've found that creating a scedule in Windows Vista+ when the system language has interesting calendars, it fails with a COM Exception refering to StartBoundary with a bad GregorianUS date.

Let's say the example of having a GregorianUS date, 26/02/2013, now we change it to ArabicSA date and it will be ##/##/14## (# is a number), and then schtasks will not accept the date.

The text conversion of dates between calendars is different on most times, however, sould the DateTime variables values of diferent calendars change? The answer is NO. The only thing that will change is the ToString way to work and format the text of the time contained.

Since schtasks only accepts GregorianUS dates, why not simply change the values assigned and bounded of StartBoundary and EndBoundary properties in Trigger.cs? The only thing needed is change ToString(V2BoundaryDateFormat) to ToString(V2BoundaryDateFormat, CultureInfo.CreateSpecificCulture("en-US"))

Lines to be changed are 252, 373 and 646 in the Trigger.cs file, after this everything Works OK.

To test the error, date time system format can be changed to Arabic, then only add a task that contains a daily schedule for example. After the changes to Trigger.cs there are no errors.

Posted this as error, don't know if it's right...!

New Post: Small code improvement in Trigger.cs

$
0
0
Thanks for solving this problem. I have incorporated your suggested changes into the code and will be testing them as part of the next release (1.9.4).

New Post: Small code improvement in Trigger.cs

$
0
0
Excelent!

And gongrats for this Project, very usefull!

New Post: Small code improvement in Trigger.cs

$
0
0
In case you are using your modified code for your project, I have already found some other related code changes. First, there is a line in Task.cs that is similar to those in Trigger.cs that needs a similar change. For every DateTime.Parse call (usually paired to the ToString calls in properties), you also need to also add the CultureInfo parameter.

New Post: Small code improvement in Trigger.cs

$
0
0
Good to know. Thinking on wait unill next release hehe :D

New Post: Create Task in Specific Folder

$
0
0
Suppose that I have a folder under the root folder called "MyFolder", how can I create task in this folder specifically ?
Viewing all 2206 articles
Browse latest View live


Latest Images