Click or drag to resize
Task Scheduler Managed Class Library

TaskEventWatcher Class

Watches system events related to tasks and issues a EventRecorded event when the filtered conditions are met.
Note  Note
Only available for Task Scheduler 2.0 on Windows Vista or Windows Server 2003 and later.
Inheritance Hierarchy
SystemObject
  SystemMarshalByRefObject
    System.ComponentModelComponent
      Microsoft.Win32.TaskSchedulerTaskEventWatcher

Namespace: Microsoft.Win32.TaskScheduler
Assembly: Microsoft.Win32.TaskScheduler (in Microsoft.Win32.TaskScheduler.dll) Version: 2.12.0
Syntax
C#
[SerializableAttribute]
[DefaultEventAttribute("EventRecorded")]
[DefaultPropertyAttribute("Folder")]
public class TaskEventWatcher : Component, 
	ISupportInitialize
Request Example View Source

The TaskEventWatcher type exposes the following members.

Constructors
 NameDescription
Public methodTaskEventWatcher Initializes a new instance of the TaskEventWatcher class. If other properties are not set, this will watch for all events for all tasks on the local machine.
Public methodTaskEventWatcher(Task) Initializes a new instance of the TaskEventWatcher class watching only those events for the specified task.
Public methodTaskEventWatcher(String, TaskService) Initializes a new instance of the TaskEventWatcher class watching only those events for the task with the provided path on the local machine.
Public methodTaskEventWatcher(TaskFolder, String, Boolean) Initializes a new instance of the TaskEventWatcher class watching only those events for the tasks whose name matches the taskFilter in the specified taskFolder and optionally all subfolders.
Public methodTaskEventWatcher(String, String, Boolean, TaskService) Initializes a new instance of the TaskEventWatcher class.
Public methodTaskEventWatcher(String, String, String, String, SecureString) Initializes a new instance of the TaskEventWatcher class on a remote machine.
Public methodTaskEventWatcher(String, String, String, String, String) Initializes a new instance of the TaskEventWatcher class on a remote machine.
Public methodTaskEventWatcher(String, String, String, Boolean, String, String, String) Initializes a new instance of the TaskEventWatcher class on a remote machine.
Top
Properties
 NameDescription
Protected propertyCanRaiseEventsGets a value indicating whether the component can raise an event.
(Inherited from Component)
Public propertyContainerGets the IContainer that contains the Component.
(Inherited from Component)
Protected propertyDesignModeGets a value that indicates whether the Component is currently in design mode.
(Inherited from Component)
Public propertyEnabled Gets or sets a value indicating whether the component is enabled.
Protected propertyEventsGets the list of event handlers that are attached to this Component.
(Inherited from Component)
Public propertyFilter Gets the filter for this TaskEventWatcher.
Public propertyFolder Gets or sets the folder to watch.
Public propertyIncludeSubfolders Gets or sets a value indicating whether to include events from subfolders when the Folder property is set. If the TaskName property is set, this property is ignored.
Public propertySiteGets or sets the ISite of the Component.
(Inherited from Component)
Public propertySynchronizingObject Gets or sets the synchronizing object.
Public propertyTargetServer Gets or sets the name of the computer that is running the Task Scheduler service that the user is connected to.
Public propertyTaskService Gets or sets the TaskService instance associated with this event watcher. Setting this value will override any values set for TargetServer, UserAccountDomain, UserName, and UserPassword and set them to those values in the supplied TaskService instance.
Public propertyUserAccountDomain Gets or sets the user account domain to be used when connecting to the TargetServer.
Public propertyUserName Gets or sets the user name to be used when connecting to the TargetServer.
Public propertyUserPassword Gets or sets the user password to be used when connecting to the TargetServer.
Top
Methods
 NameDescription
Public methodBeginInit Signals the object that initialization is starting.
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
(Inherited from MarshalByRefObject)
Public methodDisposeReleases all resources used by the Component.
(Inherited from Component)
Protected methodDispose(Boolean) Releases the unmanaged resources used by the FileSystemWatcher and optionally releases the managed resources.
(Overrides ComponentDispose(Boolean))
Public methodEndInit Signals the object that initialization is complete.
Public methodEqualsDetermines whether the specified object is equal to the current object.
(Inherited from Object)
Protected methodFinalizeReleases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection.
(Inherited from Component)
Public methodGetHashCodeServes as the default hash function.
(Inherited from Object)
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance.
(Inherited from MarshalByRefObject)
Protected methodGetServiceReturns an object that represents a service provided by the Component or by its Container.
(Inherited from Component)
Public methodGetTypeGets the Type of the current instance.
(Inherited from Object)
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance.
(Inherited from MarshalByRefObject)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object.
(Inherited from Object)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object.
(Inherited from MarshalByRefObject)
Protected methodOnEventRecorded Fires the EventRecorded event.
Public methodToStringReturns a String containing the name of the Component, if any. This method should not be overridden.
(Inherited from Component)
Top
Events
 NameDescription
Public eventDisposedOccurs when the component is disposed by a call to the Dispose method.
(Inherited from Component)
Public eventEventRecorded Occurs when a task or the task engine records an event.
Top
Remarks
Sometimes, a developer will need to know about events as they occur. In this case, they can use the TaskEventWatcher component that enables the developer to watch a task, a folder, or the entire system for filtered events.
Example

Below is information on how to watch a folder for all task events. For a complete example, look at this sample project: TestTaskWatcher.zip

C#
private TaskEventWatcher watcher;

// Create and configure a new task watcher for the task folder
private void SetupWatcher(TaskFolder tf)
{
    if (tf != null)
    {
        // Set up a watch over the supplied task folder.
        watcher = new TaskEventWatcher(tf);

        // Assign a SynchronizingObject to a local UI class to synchronize the events in this thread.
        watcher.SynchronizingObject = this;

        // Only watch for tasks that start with my company name
        watcher.Filter.TaskName = "MyCo*";

        // Only watch for task events that are informational
        watcher.Filter.EventLevels = new int[]
           { 0 /* StandardEventLevel.LogAlways */, (int)StandardEventLevel.Informational };

        // Assign an event handler for when events are recorded
        watcher.EventRecorded += Watcher_EventRecorded;

        // Start watching the folder by enabling the watcher
        watcher.Enabled = true;
    }
}

// Cleanup and release the task watcher
private void TearDownWatcher()
{
    if (watcher != null)
    {
        // Unhook the event
        watcher.EventRecorded -= Watcher_EventRecorded;
        // Stop watching for events
        watcher.Enabled = false;
        // Initiate garbage collection for the watcher
        watcher = null;
    }
}

// Update ListView instance when task events occur
private void Watcher_EventRecorded(object sender, TaskEventArgs e)
{
    int idx = IndexOfTask(e.TaskName);

    // If event is for a task we already have in the list...
    if (idx != -1)
    {
        // If event indicates that task has been deleted, remove it from the list
        if (e.TaskEvent.StandardEventId == StandardTaskEventId.TaskDeleted)
        {
            listView1.Items.RemoveAt(idx);
        }

        // If event is anything else, it most likely represents a change,
        // so update the item using information supplied through the
        // TaskEventArgs instance.
        else
        {
            var lvi = listView1.Items[idx];
            lvi.Subitems[0].Text = e.TaskName;
            lvi.Subitems[1].Text = e.Task.State.ToString();
            lvi.Subitems[2].Text = GetNextRunTimeString(e.Task);
        }
    }

    // If event is for a task we don't have in our list, add it
    else
    {
        var lvi = new ListViewItem(new string[] { e.TaskName,
     e.Task.State.ToString(), GetNextRunTimeString(e.Task) });
        listView1.Items.Add(lvi);
        listView1.Sort();
    }
}

// Get the next run time for a task
private string GetNextRunTimeString(Task t)
{
    if (t.State == TaskState.Disabled || t.NextRunTime < DateTime.Now)
        return string.Empty;
    return t.NextRunTime.ToString("G");
}
See Also