Task Scheduler API

This section describes the Task Scheduler. It contains examples as well as references for the OLE interfaces necessary to work with the Task Scheduler.

About the Task Scheduler

Programming the Task Scheduler

Task Scheduler Reference


About the Task Scheduler

The Task Scheduler allows you to perform automated tasks on a chosen computer. The Task Scheduler monitors whatever criteria you choose and executes the task when the criteria for executing the task have been met. For example, you can have the computer run ScanDisk at 7:00 P.M. every Sunday.

What Is a Task?

What Is a Trigger?

What Is an Idle Trigger?

What Is a Scheduled Work Item?

What Is a Task?

A task is any object that the Task Scheduler can execute. These include any of the following (as supported by the operating system on which the task will execute): Win32® application, Win16 application, OS/2 application, MS-DOS® application, batch file (*.bat), command file (*.cmd), or any properly registered file type. A task has one or more triggers that determine when the task should be executed.

You use the ITask interface to control and modify tasks.

What Is a Trigger?

A trigger is a set of criteria that, when met, will activate and cause a task to be executed. There are two types of triggers: time-based and event-based.

Time-based triggers activate at a specified point in time. Not only can you set the time that they become active, but you can also have them activate once, daily, weekly, monthly, on a specified day of the month (the third day of the month), or on a specified day of the week of a month (the second Tuesday of the month).

Event-based triggers activate in response to certain system events. There are event-based triggers that become active when the system starts up, when a user logs on to the local computer, or when the system becomes idle. The last of these are known as idle triggers.

You use the ITaskTrigger interface to control and modify triggers.

What Is an Idle Trigger?

When no keyboard or mouse input occurs, the computer is considered to be in an idle state. An idle trigger is an event-based trigger that becomes active a specified amount of time after the computer becomes idle. When you set the idle-related flags for a task, you create an idle trigger. You use the IScheduledWorkItem::SetIdleWait method to set the amount of time that the system is idle before the task is executed. You can use the IScheduledWorkItem::GetIdleWait method to retrieve this same value. There are three idle-related flags that can be set on a given task: TASK_FLAG_START_ONLY_IF_IDLE, TASK_FLAG_KILL_ON_IDLE_END, and TASK_FLAG_RESTART_ON_IDLE_RESUME (see ITask::SetTaskFlags).

Note The Task Scheduler service that monitors triggers on Microsoft® Windows NT® does not monitor idle conditions and does not activate any idle triggers. This does not, however, affect the task itself. The TASK_EVENT_TRIGGER_ON_IDLE trigger type and the task idle time can be set and retrieved on Windows NT. The information associated with these triggers and flags is persistent. The only difference is that, on Windows NT, the idle trigger is never activated.

What Is a Scheduled Work Item?

A scheduled work item is an item that the Task Scheduler service runs at a time specified by the item's trigger(s). Currently the only type of scheduled work item is a task.

The IScheduledWorkItem interface contains methods that are supported by all types of scheduled work items. Tasks are manipulated using the ITask interface, which derives from IScheduledWorkItem.


Programming the Task Scheduler

The collection of interfaces and methods available to the developer from the Task Scheduler represents the programmatic techniques necessary to implement the functionality of task management.

Manipulating Scheduled Work Items

Starting the Task Scheduler Service

Task Names

Task Triggers

The Starting Point: ITaskScheduler

The Target Computer

Manipulating Scheduled Work Items

The IScheduledWorkItem interface allows you to modify an existing work item's behaviors. When you have the interface pointer to IScheduledWorkItem, you have the ability to run, terminate, or modify the characteristics for a given task. The behavior and properties of each scheduled task are accessible through the IScheduledWorkItem interface.

Starting the Task Scheduler Service

The Task Scheduler service is not started by default; the developer is responsible for determining the current running state of the Task Scheduler. The following code is an example of how to start the Task Scheduler service.

//+--------------------------------------------------------------------------
//
//  Function:   StartScheduler
//
//  Synopsis:   Start the task scheduler service if it isn't already running.
//
//  Returns:    ERROR_SUCCESS or a Win32 error code.
//
//  Notes:      This function works for either Win9x or Windows NT.
//              If the service is running but paused, does nothing.
//
//---------------------------------------------------------------------------

#define SCHED_CLASS             TEXT("SAGEWINDOWCLASS")
#define SCHED_TITLE             TEXT("SYSTEM AGENT COM WINDOW")
#define SCHED_SERVICE_APP_NAME  TEXT("mstask.exe")
#define SCHED_SERVICE_NAME      TEXT("Schedule")

DWORD
StartScheduler()
{

    OSVERSIONINFO osver;

    osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);

    // Determine what version of OS we are running on.
    GetVersionEx(&osver);

    if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
    {
        // Start the Win95 version of TaskScheduler.

        HWND hwnd = FindWindow(SCHED_CLASS, SCHED_TITLE);

        if (hwnd != NULL)
        {
            // It is already running.
            return ERROR_SUCCESS;
        }

        //
        //  Execute the task scheduler process.
        //
        STARTUPINFO         sui;
        PROCESS_INFORMATION pi;

        ZeroMemory(&sui, sizeof(sui));
        sui.cb = sizeof (STARTUPINFO);

        TCHAR szApp[MAX_PATH];
        LPTSTR pszPath;

        DWORD dwRet = SearchPath(NULL,
                                 SCHED_SERVICE_APP_NAME,
                                 NULL,
                                 MAX_PATH,
                                 szApp,
                                 &pszPath);

        if (dwRet == 0)
        {
            return GetLastError();
        }

        BOOL fRet = CreateProcess(szApp,
                                  NULL,
                                  NULL,
                                  NULL,
                                  FALSE,
                                  CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP,
                                  NULL,
                                  NULL,
                                  &sui,
                                  &pi);

        if (fRet == 0)
        {
            return GetLastError();
        }

        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);

        return ERROR_SUCCESS;
    }
    else
    {

        // If not Win95 then start the NT version as a TaskScheduler service.

        SC_HANDLE   hSC = NULL;
        SC_HANDLE   hSchSvc = NULL;

        hSC = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);

        if (hSC == NULL)
        {
            return GetLastError();
        }

        hSchSvc = OpenService(hSC,
                              SCHED_SERVICE_NAME,
                              SERVICE_START | SERVICE_QUERY_STATUS);

        CloseServiceHandle(hSC);

        if (hSchSvc == NULL)
        {
            return GetLastError();
        }

        SERVICE_STATUS SvcStatus;

        if (QueryServiceStatus(hSchSvc, &SvcStatus) == FALSE)
        {
            CloseServiceHandle(hSchSvc);
            return GetLastError();
        }

        if (SvcStatus.dwCurrentState == SERVICE_RUNNING)
        {
            // The service is already running.
            CloseServiceHandle(hSchSvc);
            return ERROR_SUCCESS;
        }

        if (StartService(hSchSvc, 0, NULL) == FALSE)
        {
            CloseServiceHandle(hSchSvc);
            return GetLastError();
        }

        CloseServiceHandle(hSchSvc);

        return ERROR_SUCCESS;
    }
}

Task Names

A task name is the name of the file that stores the task information. These files all have the .job extension and reside in the Tasks folder. You can retrieve the location of the Tasks folder from the registry by getting the data for the following value:

HKEY_LOCAL_MACHINE
    SOFTWARE
        Microsoft
            SchedulingAgent
                TasksFolder

The task names are always given in wide characters, so you need to convert the string to ANSI characters if your application is not built for Unicode. The ConvertString function handles this for you.

BOOL ConvertString(LPTSTR pszOut, LPWSTR pwszIn, DWORD dwSize)
{
#ifdef UNICODE
    if(lstrcpyn(pszOut, pwszIn, dwSize))
        {
        return TRUE;
        }
#else
    if(WideCharToMultiByte( CP_ACP,
            0,
            pwszIn,
            -1,
            pszOut,
            dwSize,
            NULL,
            NULL))
        {
        return TRUE;
        }
#endif   // UNICODE

return FALSE;
}

All the Task Scheduler methods that take a task name examine the name and add the .job extension if it is not already present.

Creating Tasks

Listing the current tasks is all well and good, but how do you create your own task? There are two ways to do this. The first is to use ITaskScheduler::NewWorkItem. This method will instantiate an ITask interface and assign it the name you provide. The second is to call ITaskScheduler::AddWorkItem. When you take this route, it is your responsibility to instantiate the ITask interface and then add the task with the name you supply.

The name you supply for the task must be unique within the Tasks folder. If a task with that name already exists, ITaskScheduler::NewWorkItem and ITaskScheduler::AddWorkItem return ERROR_FILE_EXISTS. If you get this return value, you should specify a different name and attempt to add the task again.

Deleting Tasks

You use the ITaskScheduler::Delete method to delete a task. You simply supply the name of the task and, if the task is present, it will be deleted.

Editing a Task

When you are viewing the Tasks folder in Windows® Explorer, you can edit the task by double-clicking it. When you do this, the scheduling agent actually calls the tasks object's IScheduledWorkItem::EditWorkItem method. Fortunately, this method has been exposed, so you can do the same thing programmatically without having to implement all the user interface code and resources. The only thing you have to provide is a parent window handle.

For more information on editing tasks, see Task Property Sheet.

Enumerating Tasks

To enumerate tasks, call ITaskScheduler::Enum. This gives you an IEnumWorkItems interface pointer that you can use to retrieve the names of the tasks. When you have the name of a task, you can call ITaskScheduler::Activate to get the ITask interface for the task. When you have the ITask interface pointer, you can get or set any of the task information that you want. The following example enumerates all the tasks and adds them to a list view control to display them. For additional information on list views, see List View Controls.

Note Before the list view is destroyed, the release method for ITask is called for each item in the list view. The caller of ITaskScheduler::Activate is responsible for releasing the returned pointer.

BOOL LoadTaskList(HWND hwndListView)
{
HRESULT          hr;
IEnumWorkItems  *pEnum;

hr = g_pSchedulingAgent->Enum(&pEnum);
if(SUCCEEDED(hr))
    {
    LPWSTR   *ppNames;
    DWORD    dwFetched;

    while(SUCCEEDED(pEnum->Next(5, &ppNames, &dwFetched)) && dwFetched)
        {
        DWORD i;
        TCHAR szString[MAX_PATH];

        for(i = 0; i < dwFetched; i++)
            {
            if(ConvertString(szString, *(ppNames + i), sizeof(szString)))
                {
                LV_ITEM  lvItem;
                ITask *pTask;

                ZeroMemory(&lvItem, sizeof(lvItem));
                lvItem.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM;
                lvItem.pszText = szString;
                lvItem.iImage = I_IMAGECALLBACK;
                lvItem.iItem = ListView_GetItemCount(hwndListView);

                // Get the ITask for this task.
                hr = g_pSchedulingAgent->Activate(  *(ppNames + i),
                        IID_ITask,
                        (LPUNKNOWN*)&pTask);
                if(SUCCEEDED(hr))
                    {
                lvItem.lParam = (LPARAM)pTask;

                // Add the item to the list.
                ListView_InsertItem(hwndListView, &lvItem);
                }
            }

            // Free the string.
            CoTaskMemFree(*(ppNames + i));
            }

        // Free the array.
        CoTaskMemFree(ppNames);
        }

    pEnum->Release();
    return TRUE;
    }

return FALSE;
}

Executing and Terminating a Task

If you want to programmatically cause a task to run, you simply call the task object's IScheduledWorkItem::Run method. This method attempts to execute the task and returns as soon as the task has started. The Task Scheduler service must be running for this method to succeed.

If it becomes necessary for you to terminate a running task, you can use IScheduledWorkItem::Terminate. This method attempts to terminate the task and returns a success/failure code, informing your application if it was successful or not. IScheduledWorkItem::Terminate attempts to gracefully shut down the application by sending it a WM_CLOSE message. It then waits approximately three minutes for the process to terminate. If the process has not terminated within that three minutes, IScheduledWorkItem::Terminate uses TerminateProcess to terminate the task. As you can see, there is potential here for data loss if the application must be terminated the hard way. Therefore, you should avoid terminating tasks if at all possible.

Manipulating Tasks: ITask

ITask is the interface you use to control a task object. You can set and retrieve all of the task's information, execute and terminate the task, add and delete triggers, and even allow the user to modify the task with a standard user interface.

ITask implements all the methods necessary to set and retrieve all of the task's information. For a complete list of the methods for affecting the task, see the ITask references. The method names are rather self-explanatory.

Task Property Sheet

The IProvideTaskPage::GetPage method provides the ability to retrieve the property sheet page associated with a task object. The information for the task object's general page, schedule, and settings is available from the GetPage method.

VOID EditTaskSettings(ITask *pTask)
{
    IProvideTaskPage   *ptp;
    PROPSHEETHEADER     psh;
    HPROPSHEETPAGE      hpage;

    // Display the "Settings" property page.
    pTask->QueryInterface(IID_IProvideTaskPage, (VOID**)(IProvideTaskPage**)&ptp);

    // The settings will be saved to the task object on release.
    ptp->GetPage(TASKPAGE_SETTINGS, TRUE, &hpage);

    // Display the page in its own property sheet.
    psh.dwSize=sizeof(PROPSHEETHEADER);
    psh.dwFlags=PSH_DEFAULT;
    psh.hwndParent=NULL;
    psh.hInstance=NULL;
    psh.pszCaption=TEXT("Just the settings page on the task object");
    psh.phpage=&hpage;
    psh.nPages=1;

    PropertySheet(&psh);
}

Task Triggers

Applications can use the methods available from the task scheduler interfaces to access, set, or modify the trigger for a task. Triggers specify task start times, repetition criteria, and other parameters.

Creating and Deleting Triggers

When you use IScheduledWorkItem::CreateTrigger, you are creating a brand new ITaskTrigger object. IScheduledWorkItem::CreateTrigger gives you both the new trigger's numeric index and the ITaskTrigger interface pointer. You can then use this interface to modify the trigger parameters. By the same token, IScheduledWorkItem::DeleteTrigger deletes the trigger that has the numeric index specified.

Manipulating Triggers: ITaskTrigger

The ITaskTrigger interface allows you to modify an existing trigger's parameters, but how do you get the ITaskTrigger interface for a trigger object? There are two ways to do this:

  • Create a new trigger using IScheduledWorkItem::CreateTrigger.
  • Use IScheduledWorkItem::GetTrigger. This method takes the desired trigger's numerical index.

When you have the interface, you can use ITaskTrigger::SetTrigger to set the trigger information and ITaskTrigger::GetTrigger to get the trigger object's information. ITaskTrigger::GetTriggerString gives you a formatted string describing the trigger. You can use this string to display information about the trigger.

The Starting Point: ITaskScheduler

The ITaskScheduler interface is the starting point for programming the Task Scheduler. ITaskScheduler allows you to enumerate, add, modify, and delete tasks, and administer tasks on another computer. All you have to do to obtain the ITaskScheduler interface is to call CoCreateInstance with the scheduling agent class identifier and interface identifier. The following example shows how this is done.

#include <mstask.h>

ITaskScheduler  *g_pSchedulingAgent;

BOOL Initialize(void)
{
HRESULT  hr;

CoInitialize(NULL);

hr = CoCreateInstance( CLSID_CSchedulingAgent,
            NULL,
            CLSCTX_INPROC_SERVER,
            IID_ITaskScheduler,
            (LPVOID*)&g_pSchedulingAgent);

return SUCCEEDED(hr);
}

When you no longer need the ITaskScheduler interface, simply call its Release method. All of the methods contained within the IUnknown interface are inherited in ITaskScheduler; these include QueryInterface, AddRef, and Release. Don't forget that you need to call CoInitialize or OleInitialize before calling CoCreateInstance. Also, be sure to call CoUninitialize or OleUninitialize when you are done using OLE.

The Target Computer

In Task Scheduler terms, the target computer is the computer to which any instance of the ITaskScheduler interface is associated. All of the tasks that each instance of the ITaskScheduler interface controls are stored on the target computer and will run on the target computer. When you create a new instance of ITaskScheduler, the local computer is the target computer by default.

You can use ITaskScheduler to administer tasks on a remote computer. There are constraints for remote task administration:

  • You can view tasks on a remote computer running Windows NT® only if you are an administrator on that remote computer.
  • You can edit tasks on a remote Windows® 95 computer only if that remote computer has remote registry software installed and shares the x$ share, where x is the hard drive on which the Tasks folder resides.
  • A computer running Windows 95 must have the remote registry service installed before it can set the target computer to a remote computer, or be specified as a remote target computer.

    For more information on installing the remote registry service, see article Q141460 in the Microsoft Knowledge Base.

You use ITaskScheduler::SetTargetComputer to change the target computer and ITaskScheduler::GetTargetComputer to get the name of the target computer. Computer names are always in Universal Naming Convention (UNC) format.


Task Scheduler Reference

This reference describes the programming elements that are used and/or implemented by the Task Scheduler.

Interfaces

Structures

Unions

Enumerated Types


Interfaces

The interfaces and methods described in the following sections illustrate the necessary implementations of functionality available within the Task Scheduler. Many of these same task options are available to the user from the Scheduled Tasks user interface.

The collection of interfaces and methods available to the developer from Task Scheduler represents the programmatic techniques necessary to implement the functionality of task management.

IEnumWorkItems
IProvideTaskPage
IScheduledWorkItem
ITaskScheduler
ITask
ITaskTrigger


IEnumWorkItems

Applications use the methods of the IEnumWorkItems interface to enumerate tasks. The following list of methods is organized in vtable order.

IEnumWorkItems methods
Next
Skip
Reset
Clone


IEnumWorkItems::Clone

HRESULT Clone(
    IEnumWorkItems ** ppEnumWorkItems
);

Creates another enumerator that contains the same enumeration state as the current one. Using this method, a client can record a particular point in the enumeration sequence and return to that point later. The new enumerator supports the same interface as the original.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The argument is not valid.
    E_OUTOFMEMORY | There is not enough memory available.
    E_UNEXPECTED | An error occurred.
ppEnumWorkItems
Address of a pointer to an IEnumWorkItems interface that will be assigned to the newly created enumeration. If the method fails, this parameter is undefined.

Back to top


IEnumWorkItems::Next

HRESULT Next(
    ULONG celt,
    LPWSTR ** rgpwszNames,
    ULONG * pceltFetched
);

Retrieves the next celt tasks in the enumeration sequence. If there are fewer than the requested number of elements left in the sequence, the remaining elements are retrieved.

  • Returns one of the following values:
    S_OK | The number of tasks retrieved equals the number requested.
    S_FALSE | The number returned is less than the number requested (thus there are no more tasks to enumerate).
    E_INVALIDARG | A parameter is invalid.
    E_OUTOFMEMORY | Not enough memory is available.
celt
Number of tasks to retrieve.
rgpwszNames
Address of an array of pointers to character strings that contain the file names of the tasks returned from the enumeration sequence. These file names are taken from the Tasks folder and have the .job extension. You must free each LPWSTR in the array and the array itself using CoTaskMemFree.
pceltFetched
Address of a value that contains the number of tasks returned in rgpwszNames. If the celt parameter is 1, this parameter can be NULL.


IEnumWorkItems::Reset

HRESULT Reset(void);

Resets the enumeration sequence to the beginning.

  • Returns S_OK if successful, or E_OUTOFMEMORY if there is not enough available memory.

A call to this method does not guarantee that the same set of tasks will be enumerated after the reset, because it depends on the collection being enumerated.


IEnumWorkItems::Skip

HRESULT Skip(
    ULONG celt
);

Skips the next celt number of tasks in the enumeration sequence.

  • Returns one of the following values:
    S_OK | The number of elements skipped equals celt.
    S_FALSE | The number of elements remaining in the sequence is less than celt.
    E_INVALIDARG | celt is less than or equal to zero.
celt
Number of tasks to be skipped.


IProvideTaskPage

Applications use the method of the IProvideTaskPage interface to have access to the task object's property sheet settings.

IProvideTaskPage method
GetPage


IProvideTaskPage::GetPage

HRESULT IProvideTaskPage::GetPage(
    TASKPAGE tpType,
    BOOL  fPersistChanges,
    HPROPSHEETPAGE * phPage
);

Provides the ability to retrieve one or more property sheet pages associated with a task object.

  • Returns S_OK if the method was successful, or STG_E_NOTFILEBASEDSTORAGE if the task has not been saved to disk.
tpType
Specific page to return. The page type is one of the enumerated types of TASKPAGE defined as:
TASKPAGE_TASK | General page property.
TASKPAGE_SCHEDULE | Schedule properties for the task object.
TASKPAGE_SETTINGS | Settings properties for the task object.
fPersistChanges
If TRUE, the page updates the persisted task object automatically if there is a change made on release. If FALSE, the caller is responsible for persisting task object changes by calling IPersistFile::Save on the task object.
phPage
Returned page handle for the task object.

See also TASKPAGE


IScheduledWorkItem

Applications use the methods of the IScheduledWorkItem interface to control work items. The following list of methods is organized in vtable order.

IScheduledWorkItem methods
CreateTrigger
DeleteTrigger
GetTriggerCount
GetTrigger
GetTriggerString
GetRunTimes
GetNextRunTime
SetIdleWait
GetIdleWait
Run
Terminate
EditWorkItem
GetMostRecentRunTime
GetStatus
GetExitCode
SetComment
GetComment
SetCreator
GetCreator
SetWorkItemData
GetWorkItemData
SetErrorRetryCount
GetErrorRetryCount
SetErrorRetryInterval
GetErrorRetryInterval
SetFlags
GetFlags
SetAccountInformation
GetAccountInformation


IScheduledWorkItem::CreateTrigger

HRESULT CreateTrigger(
    WORD * piNewTrigger,
    ITaskTrigger ** ppTrigger
);

Creates a task trigger.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
piNewTrigger
Address of a value that specifies the new trigger. piNewTrigger receives the new trigger index value. DeleteTrigger would take this value to delete the trigger.
ppTrigger
Address of a pointer to an ITaskTrigger interface.

See also IScheduledWorkItem::DeleteTrigger


IScheduledWorkItem::DeleteTrigger

HRESULT DeleteTrigger(
    WORD iTrigger
);

Deletes a task trigger.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
iTrigger
Value that specifies the trigger to be deleted. The value associated with a trigger is established when a trigger is created by CreateTrigger.

See also IScheduledWorkItem::CreateTrigger


IScheduledWorkItem::EditWorkItem

HRESULT EditWorkItem(
    HWND  hParent,
    DWORD dwReserved
);

Opens the configuration properties for the work item.

  • Returns one of the following values:
    S_OK | The operation was successful.
    STG_E_NOTFILEBASEDSTORAGE | The task object is not persistent.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
hParent
Handle to the parent window of the configuration properties window.
dwReserved
Reserved for internal use; this must be zero.

When you open the Properties page for a task from Windows®, the Task Scheduler calls this method to display the task's properties.


IScheduledWorkItem::GetAccountInformation

HRESULT GetAccountInformation(
    LPWSTR * ppwszAccountName
);

Retrieves the account name for the task. This method is for Windows NT®; on Windows® 9x, this method will return SCHED_E_NO_SECURITY_SERVICES, indicating the Task Scheduler security services are not available. The Task Scheduler service must be running for this method to succeed.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
    SCHED_E_NO_SECURITY_SERVICES | Security services are available only on Windows NT®.
ppwszAccountName
Address of an LPWSTR that contains the account name for the current task.

The method that invokes GetAccountInformation is responsible for freeing the string using the CoTaskMemFree function.

See also IScheduledWorkItem::SetAccountInformation


IScheduledWorkItem::GetComment

HRESULT GetComment(
    LPWSTR * ppwszComment
);

Retrieves the comment for the work item.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
ppwszComment
Character string that contains the comment retrieved from the current work item.


IScheduledWorkItem::GetCreator

HRESULT GetCreator(
    LPWSTR * ppwszCreator
);

Retrieves the work item's creator.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
ppwszCreator
Address of an LPWSTR that contains the current task's creator. The method that invokes GetCreator is responsible for freeing this string using the CoTaskMemFree function.

See also IScheduledWorkItem::SetCreator


IScheduledWorkItem::GetErrorRetryCount IScheduledWorkItem::GetErrorRetryCount *
  * Previous Topic: IScheduledWorkItem::GetCreator
  * Next Topic: IScheduledWorkItem::GetErrorRetryInterval

IScheduledWorkItem::GetErrorRetryCount

HRESULT GetErrorRetryCount(
    WORD * pwRetryCount
);

Not currently implemented.


IScheduledWorkItem::GetErrorRetryInterval

HRESULT GetErrorRetryInterval(
    WORD * pwRetryInterval
);

Not currently implemented. Retrieves the time interval, in minutes, between task retries after an error occurs.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
    E_NOTIMPL | Not implemented.
pwRetryInterval
Address of a value that contains the time interval between retries of the current task after an error occurs.

See also IScheduledWorkItem::SetErrorRetryInterval


IScheduledWorkItem::GetExitCode

HRESULT GetExitCode(
    DWORD * pdwExitCode
);

Retrieves the work item's last exit code.

  • Returns the error from the last attempt to start the work item. Possible values include:
    S_OK | The attempt to start the work item was successful.
    SCHED_S_TASK_HAS_NOT_RUN | No attempt has ever been made to start this work item.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pdwExitCode
Address of a value that is set to the exit code that the work item returned when it last stopped running. If the work item has never been started, this will be set to zero.


IScheduledWorkItem::GetFlags

HRESULT GetFlags(
    DWORD * pdwFlags
);

Returns the flags that modify the task's behavior.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pdwFlags
Address of a value that contains the description of how the task behaves. For a list of the flags, see IScheduledWorkItem::SetFlags.


IScheduledWorkItem::GetIdleWait

HRESULT GetIdleWait(
    WORD * pwIdleMinutes,
    WORD * pwDeadlineMinutes
);

Retrieves the task's idle wait time.

  • Returns S_OK if successful, or E_INVALIDARG if the argument is not valid.
pwIdleMinutes
Address of a value that contains the current task's idle wait time.
pwDeadlineMinutes
Address of a value that specifies the maximum number of minutes to wait for the idle time duration contained in pwIdleMinutes to occur before running the task.

If the task has the TASK_EVENT_TRIGGER_ON_IDLE trigger, the task runs when pwIdleMinutes have elapsed since the most recent keyboard or mouse event.

If the TASK_FLAG_START_ONLY_IF_IDLE flag is set, the task will run only after a period of pwDeadlineMinutes have elapsed with no mouse or keyboard activity. The Task Scheduler service will wait up to pwDeadlineMinutes past the scheduled start time of the task for the required pwIdleMinutes of idle time to elapse.

See also IScheduledWorkItem::SetIdleWait, Idle Triggers


IScheduledWorkItem::GetMostRecentRunTime

HRESULT GetMostRecentRunTime(
    SYSTEMTIME * pstLastRun
);

Retrieves the most recent time the work item began running.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
    SCHED_S_TASK_HAS_NOT_RUN | The task has never run.
pstLastRun
Address of a SYSTEMTIME structure that contains the most recent time the current task ran.

See also IScheduledWorkItem::GetNextRunTime


IScheduledWorkItem::GetNextRunTime

HRESULT GetNextRunTime(
    [in, out] SYSTEMTIME * pstNextRun
);

Retrieves the next time the work item will run.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pstNextRun
Address of a SYSTEMTIME structure that contains the next time the work item will run.


IScheduledWorkItem::GetRunTimes

HRESULT GetRunTimes(
    const LPSYSTEMTIME pstBegin,
    const LPSYSTEMTIME pstEnd,
    WORD * pCount,
    LPSYSTEMTIME * rgstTaskTimes
);

Retrieves the work item run times for a specified time period.

  • Returns one of the following values:
    S_OK | The requested number of run times was retrieved.
    S_FALSE | The method succeeded, but fewer than the requested number of run times was retrieved. The number of run times retrieved is contained in the value pointed to by pCount. If the number of run times retrieved is zero, there are also no event-based triggers that can cause the work item to be executed during the specified time period.
    SCHED_S_EVENT_TRIGGER | No run times exist for the specified time period, but event-based triggers exist that might cause the work item to run during the specified time period.
    SCHED_S_TASK_NO_VALID_TRIGGERS | The work item is enabled but has no valid triggers.
    SCHED_S_TASK_DISABLED | The work item is disabled.
    E_INVALIDARG | One or more of the arguments are invalid.
    E_OUTOFMEMORY | There is insufficient memory to compute the result.
pstBegin
Address of a SYSTEMTIME structure that contains the starting time of the time period to check. This value is inclusive.
pstEnd
Address of a SYSTEMTIME structure that contains the ending time of the time period to check. This value is exclusive. If NULL is passed for this value, the end time is infinite.
pCount
Address of a value that specifies the number of run times to retrieve. Before calling GetRunTimes, this value contains the number of run times being requested. This can be a number between 1 and TASK_MAX_RUN_TIMES. After GetRunTimes is called, this value contains the number of run times actually retrieved.
rgstTaskTimes
Address of an array of SYSTEMTIME structures. This array contains pCount run times. This array must be freed using the CoTaskMemFree function.


IScheduledWorkItem::GetStatus

HRESULT GetStatus(
    HRESULT * phrStatus
);

Retrieves the status of the work item.

  • Returns S_OK if the operation was successful, or E_INVALIDARG if the arguments are not valid.
phrStatus
Address of a value that contains the status of the current work item. phrStatus can be set to one of the following values:
SCHED_S_TASK_READY | Task is ready to run at its next scheduled time.
SCHED_S_TASK_RUNNING | Task is currently running.
SCHED_S_TASK_NOT_SCHEDULED | One or more of the properties that are needed to run this task on a schedule have not been set.


IScheduledWorkItem::GetTrigger

HRESULT GetTrigger(
    WORD iTrigger,
    ITaskTrigger ** ppTrigger
);

Retrieves a task trigger.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
iTrigger
Value that specifies which trigger to retrieve.
ppTrigger
Address of a pointer to an ITaskTrigger interface. This interface contains the retrieved trigger.


IScheduledWorkItem::GetTriggerCount

HRESULT GetTriggerCount(
    WORD * plCount
);

Retrieves the number of triggers for the current task.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
plCount
Address of a value that contains the total count of all triggers that are currently associated with the task.


IScheduledWorkItem::GetTriggerString

HRESULT GetTriggerString(
    WORD iTrigger,
    LPWSTR * ppwszTrigger
);

Retrieves a character string that describes the task trigger.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
iTrigger
Value that specifies which trigger to retrieve.
ppwszTrigger
Address of a character string that contains the retrieved trigger description.


IScheduledWorkItem::GetWorkItemData

HRESULT GetWorkItemData(
    WORD * pcBytes,
    BYTE ** ppBytes
);

Retrieves application-defined data associated with the work item.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pcBytes
Number of bytes copied.
ppBytes
Address of a BYTE pointer that contains user-defined data for the current task. The method that invokes GetWorkItemData is responsible for freeing this memory by using CoTaskMemFree.

See also IScheduledWorkItem::SetWorkItemData


IScheduledWorkItem::Run

HRESULT Run(void);

Runs the work item. The Task Scheduler service must be running for this method to succeed.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.


IScheduledWorkItem::SetAccountInformation

HRESULT SetAccountInformation(
    LPCWSTR pwszAccountName,
    LPCWSTR pwszPassword
);

Sets the account name and password for the task. This method is for Windows NT®; on Windows® 9x, this method will return SCHED_E_NO_SECURITY_SERVICES, indicating the Task Scheduler security services are not available. The Task Scheduler service must be running for this method to succeed.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
    SCHED_E_NO_SECURITY_SERVICES | Security services are available only on Windows NT.
pwszAccountName
LPCWSTR that contains the account name. This account name is assigned to the current task.
pwszPassword
LPCWSTR that contains the account password. This password is assigned to the current task.

See also IScheduledWorkItem::GetAccountInformation


IScheduledWorkItem::SetComment

HRESULT SetComment(
    LPCWSTR pwszComment
);

Sets the comment for the work item.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pwszComment
Character string containing the comment to assign to the current work item.


IScheduledWorkItem::SetCreator

HRESULT SetCreator(
    LPCWSTR pwszCreator
);

Sets the work item's creator.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pwszCreator
LPCWSTR that contains the work item's creator.

See also IScheduledWorkItem::GetCreator


IScheduledWorkItem::SetErrorRetryCount

HRESULT SetErrorRetryCount(
    WORD wRetryCount
);

Not currently implemented. Sets the number of times the task will try to run again if an error occurs.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
    E_NOTIMPL | Not implemented.
wRetryCount
Value assigned as the number of error retries for the current task.

See also IScheduledWorkItem::GetErrorRetryCount


IScheduledWorkItem::SetErrorRetryInterval

HRESULT SetErrorRetryInterval(
    WORD wRetryInterval
);

Not currently implemented. Sets the time interval, in minutes, between task retries after an error occurs.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
    E_NOTIMPL | Not implemented.
wRetryInterval
Value assigned as the interval between error retries for the current task.

See also IScheduledWorkItem::GetErrorRetryInterval


IScheduledWorkItem::SetFlags

HRESULT SetFlags(
    DWORD dwFlags
);

Sets the flags that modify the task's behavior.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
dwFlags
Value that contains a combination of one or more of the following flags:
TASK_FLAG_INTERACTIVE
This task flag is used when converting Windows NT AT service jobs into tasks. The Windows NT AT service job refers to At.exe, the Windows NT command-line utility used for creating jobs for the Windows NT Schedule service. The Task Scheduler service replaces the Schedule service and is backward-compatible with it. This conversion occurs when the Task Scheduler is installed on Windows NT; for example, installing Internet Explorer 4.0, or upgrading to Windows NT 5. During the setup process, the Task Scheduler installation code searches the registry for jobs created for the AT service, and creates tasks that will accomplish the same operation.

For such converted jobs, the interactive flag is set if the task is intended to be displayed to the user. When this flag is not set, no task items are displayed in the Tasks folder, and no user interface associated with the task is presented to the user when the task is executed.

TASK_FLAG_DELETE_WHEN_DONE
Task will be deleted when there are no more scheduled run times.
TASK_FLAG_DISABLED
Task is disabled. This is useful to temporarily prevent a task from running at the scheduled time(s).
TASK_FLAG_HIDDEN
Task file is hidden. When the task begins execution, it runs in a hidden window.
TASK_FLAG_START_ONLY_IF_IDLE
Task begins only if the computer is not in use at the scheduled start time. Windows 95 only.
TASK_FLAG_KILL_ON_IDLE_END
Task terminates if the computer makes an idle to non-idle transition while the task is running. The computer is not considered idle until the IdleWait triggers' time elapses with no user input. Windows 95 only. For information regarding idle triggers, see Idle Triggers.
TASK_FLAG_RESTART_ON_IDLE_RESUME
Task starts again if the computer makes a non-idle to idle transition before all its triggers' dwMinutesDuration elapse. (Use this flag in conjunction with TASK_FLAG_KILL_ON_IDLE_END.) Windows 95 only.
TASK_FLAG_DONT_START_IF_ON_BATTERIES
Task does not start if its target computer is running on battery power. Windows 95 only.
TASK_FLAG_KILL_IF_GOING_ON_BATTERIES
Task ends and the associated application quits if the task's target computer switches to battery power. Windows 95 only.
TASK_FLAG_RUN_IF_CONNECTED_TO_INTERNET
Task runs only if there is currently a valid Internet connection. Note: This feature is currently not implemented.

See also IScheduledWorkItem::GetFlags


IScheduledWorkItem::SetIdleWait

HRESULT SetIdleWait(
    WORD wIdleMinutes,
    WORD wDeadlineMinutes
);

Sets the idle wait time for the task.

  • Returns S_OK.
wIdleMinutes
Value of the task's idle wait time, in minutes.
wDeadlineMinutes
Value that specifies the maximum number of minutes to wait for the idle wait time duration contained in wIdleMinutes to occur before running the task.

If the task has the TASK_EVENT_TRIGGER_ON_IDLE trigger, the task runs when wIdleMinutes have elapsed since the most recent keyboard or mouse event.

If the TASK_FLAG_START_ONLY_IF_IDLE flag is set, the task runs only after a period of wIdleMinutes elapses with no mouse or keyboard activity. The Task Scheduler service will wait up to wDeadlineMinutes past the scheduled start time of the task for the required wIdleMinutes of idle time to elapse.

See also IScheduledWorkItem::GetIdleWait, Idle Triggers


IScheduledWorkItem::SetWorkItemData

HRESULT SetWorkItemData(
    WORD cBytes,
    BYTE rgbData[]
);

Stores application-defined data associated with the work item.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
cBytes
Number of bytes in the data buffer. The caller allocates and frees this memory.
rgbData
Data to copy.

See also IScheduledWorkItem::GetWorkItemData


IScheduledWorkItem::Terminate

HRESULT Terminate(void);

Ends the execution of the work item.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.


ITaskScheduler

Applications use the methods of the ITaskScheduler interface to schedule tasks. The following list of methods is organized in vtable order.

ITaskScheduler methods
SetTargetComputer
GetTargetComputer
Enum
Activate
Delete
NewWorkItem
AddWorkItem
IsOfType


ITaskScheduler::Activate

HRESULT Activate(
    LPCWSTR pwszName,
    REFIID riid,
    IUnknown ** ppunk
);

Returns an active interface to the specified task.

  • Returns one of the following values:
    S_OK | The method was successful.
    SCHED_E_UNKNOWN_OBJECT_VERSION | The task object version is either unsupported or invalid.
    E_INVALIDARG | pwszName is not valid.
    E_OUTOFMEMORY | A memory allocation failure occurred.
pwszName
LPCWSTR that specifies the name of the task to activate.
riid
Reference identifier of the interface being requested.
ppunk
Address of an interface pointer that receives the requested interface.


ITaskScheduler::AddWorkItem

HRESULT AddWorkItem(
    LPCWSTR  pwszTaskName,
    IScheduledWorkItem * pWorkItem
);

Adds a task to the schedule of tasks. Unlike NewWorkItem, this method requires that you first create an object that supports the IScheduledWorkItem interface and pass its address in the pWorkItem parameter.

  • Returns one of the following values:
    S_OK | The operation was successful.
    ERROR_FILE_EXISTS | A task with the specified name already exists.
    E_INVALIDARG | One or more of the arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available to complete the operation.
pwszTaskName
LPCWSTR that specifies the name of the task to add. The task name must conform to Windows NT file-naming conventions but cannot include backslashes, because nesting within the task folder object is not allowed.
pWorkItem
Address of an interface pointer that receives the requested interface.

See also ITaskScheduler::NewWorkItem


ITaskScheduler::Delete

HRESULT Delete(
    LPCWSTR pwszName
);

Deletes a task.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pwszName
LPCWSTR that specifies the name of the task to delete.


ITaskScheduler::Enum

HRESULT Enum(
    IEnumTasks ** ppEnumTasks
);

Retrieves a pointer to an OLE enumerator object that enumerates the tasks in the current task folder.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
ppEnumTasks
Address of a pointer to an IEnumWorkItems interface. This interface contains the enumeration context of the current task(s).

The current folder resides on the computer returned by GetTargetComputer, which defaults to the local computer if not previously set by a call to SetTargetComputer.


ITaskScheduler::GetTargetComputer

HRESULT GetTargetComputer(
    LPWSTR * ppwszComputer
);

Returns the computer name on which ITaskScheduler is currently targeted.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
ppwszComputer
Address of an LPWSTR that contains the name of the target computer for the current task. This string is allocated by the method that invokes GetTargetComputer and is freed by the same method by using CoTaskMemFree.


ITaskScheduler::IsOfType

HRESULT IsOfType(
    LPCWSTR  pwszName,
    REFIID   riid
);

Checks the object's type to verify that it supports a particular interface.

  • Returns S_OK if the object named by pwszName supports the interface specified in riid, or S_FALSE otherwise.
pwszName
LPCWSTR that specifies the name of the object to check.
riid
Identifier of the interface to be matched.


ITaskScheduler::NewWorkItem

HRESULT NewWorkItem(
    LPCWSTR    pwszTaskName,
    REFCLSID   rclsid,
    REFIID     riid,
    IUnknown   ** ppunk
);

Allocates space for a new task and retrieves its address. Unlike AddWorkItem, this function handles memory allocation automatically.

  • Returns one of the following values:
    S_OK | The operation was successful.
    ERROR_FILE_EXISTS | A task with the specified name already exists.
    E_INVALIDARG | One or more of the arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available to complete the operation.
pwszTaskName
LPCWSTR that specifies the new task's name. The task name must conform to Windows NT file-naming conventions but cannot include backslashes, because nesting within the task folder object is not allowed.
rclsid
Identifier of the class of work item to be created. The only supported class is CLSID_Ctask.
riid
Reference identifier of the interface being requested.
ppunk
Address of an interface pointer that receives the requested interface.

See also ITaskScheduler::AddWorkItem


ITaskScheduler::SetTargetComputer

HRESULT SetTargetComputer(
    LPCWSTR pwszComputer
);

Selects the computer that the ITaskScheduler interface operates on. This allows remote task management and enumeration. The user must have administrative access on the remote computer to use this method. For more information on remote installation requirements, refer to Mstask.hlp.

  • Returns one of the following values:
    S_OK | The method was successful.
    SCHED_E_SERVICE_NOT_INSTALLED | The Task Scheduler service is not installed on the target computer.
    E_INVALIDARG | pwszComputer is not valid.
    E_OUTOFMEMORY | A memory allocation failure occurred.
pwszComputer
LPCWSTR that specifies the target computer for the current task. The computer name indicates that the local computer is the target computer; set this value to NULL or to the local computer's Universal Naming Convention (UNC) name.


ITask

Applications use the methods of the ITask interface to set and retrieve task information and to run and terminate tasks. The following list of methods is organized in vtable order.

ITask methods
SetApplicationName
GetApplicationName
SetParameters
GetParameters
SetWorkingDirectory
GetWorkingDirectory
SetPriority
GetPriority
SetTaskFlags
GetTaskFlags
SetMaxRunTime
GetMaxRunTime


ITask::GetApplicationName

HRESULT GetApplicationName(
    LPWSTR * ppwszApplicationName
);

Retrieves the name of the application that the task is associated with.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
ppwszApplicationName
Address of an LPWSTR that contains the name of the application the current task is associated with. The method that invokes GetApplicationName is responsible for freeing this string using the CoTaskMemFree function.

If you set the application name property to an executable file, you can set the parameters property to the command-line arguments to pass to that executable—for example, ApplicationName=notepad.exe and Parameters=foo.txt.

However, if you set the ApplicationName property to a non-executable file, the parameters property will be ignored, because the application name in this case is the parameter—for example, ApplicationName=foo.txt.

See also ITask::SetApplicationName


ITask::GetMaxRunTime

HRESULT GetMaxRunTime(
    DWORD * pdwMaxRunTime
);

Retrieves the maximum time, in milliseconds, the task can run before terminating.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pdwMaxRunTime
Address of a value that contains the maximum run time of the current task.

If the maximum run time is reached during the execution of a task, the Scheduling Agent first sends a WM_CLOSE message to the associated application. If the application hasn't exited within three minutes, TerminateProcess is run.

See also ITask::SetMaxRunTime


ITask::GetParameters

HRESULT GetParameters(
    LPWSTR * ppwszParameters
);

Retrieves the task's command-line parameters.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
ppwszParameters
Address of an LPWSTR that contains the current task's parameters. The method that invokes GetParameters is responsible for freeing this string using the CoTaskMemFree function.

See also ITask::SetParameters


ITask::GetPriority

HRESULT GetPriority(
    DWORD * pdwPriority
);

Retrieves the priority for the task.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pdwPriority
Address of a DWORD that contains the priority for the current task. The priority value determines the frequency and length of a process' time slices. This applies only to Windows NT and has no effect in Windows 95. It is taken from the CreateProcess priority class and can be one of the following flags (in descending order of thread scheduling priority):
REALTIME_PRIORITY_CLASS
HIGH_PRIORITY_CLASS
NORMAL_PRIORITY_CLASS
IDLE_PRIORITY_CLASS

See also ITask::SetPriority


ITask::GetTaskFlags

HRESULT GetTaskFlags(
    DWORD * pdwFlags
);

Returns the flags that modify the task's behavior.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pdwFlags
Address of a value that contains the description of how the task behaves. For a list of the flags, see ITask::SetTaskFlags.


ITask::GetWorkingDirectory

HRESULT GetWorkingDirectory(
    LPWSTR * ppwszWorkingDirectory
);

Retrieves the task's working directory.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
ppwszWorkingDirectory
Address of an LPWSTR that contains the task's working directory. The method that invokes GetWorkingDirectory is responsible for freeing this string using the CoTaskMemFree function.

See also ITask::SetWorkingDirectory


ITask::SetApplicationName

HRESULT SetApplicationName(
    LPCWSTR pwszApplicationName
);

Assigns a specific application to the current task.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pwszApplicationName
LPCWSTR that contains an application's name. To clear the application name, set pwszApplicationName to L"".

If you do not specify a path for the application, the Task Scheduler searches the environment path to find the correct path. If the application name specifies a program, it should use the .exe extension to ensure that the Scheduling Agent user interface properly displays the application's icon.

See also ITask::GetApplicationName


ITask::SetMaxRunTime

HRESULT SetMaxRunTime(
    DWORD dwMaxRunTime
);

Sets the maximum time the task can run before terminating.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
dwMaxRunTime
Value assigned as the maximum run time, in milliseconds, for the current task.

If the maximum run time is reached during the execution of a task, the Scheduling Agent first sends a WM_CLOSE message to the associated application. If the application has not exited within three minutes, TerminateProcess is run.

See also ITask::GetMaxRunTime


ITask::SetParameters

HRESULT SetParameters(
    LPCWSTR pwszParameters
);

Sets the command-line parameters for the task.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pwszParameters
LPCWSTR that contains task parameters. These parameters are passed as command-line arguments to the application the task will run.

If the Application Name method contains a document to run by association, the Parameters methods are ignored. To clear the command-line parameter property, set pwszParameters to L"".

The application name and parameters properties are accessed through the Application Name Set and Get methods on the ITask interface. They are properties of a task object.

See also ITask::GetParameters


ITask::SetPriority

HRESULT SetPriority(
    DWORD dwPriority
);

Sets the priority for the task.

  • Returns S_OK if successful, or E_INVALIDARG if the argument is not valid.
dwPriority
Value assigned as the priority for the current task. The priority value determines the frequency and length of a process' time slices. This applies only to Windows NT and has no effect in Windows 95. It is taken from the CreateProcess priority class and can be one of following flags (in descending order of thread scheduling priority):
REALTIME_PRIORITY_CLASS
HIGH_PRIORITY_CLASS
NORMAL_PRIORITY_CLASS
IDLE_PRIORITY_CLASS

See also ITask::GetPriority


ITask::SetTaskFlags

HRESULT SetTaskFlags(
    DWORD dwFlags
);

Sets the flags that modify the task's behavior.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
dwFlags
Value that contains a combination of one or more of the following flags:
TASK_FLAG_INTERACTIVE
This task flag is used when converting Windows NT AT service jobs into tasks. The Windows NT AT service job refers to At.exe, the Windows NT command-line utility used for creating jobs for the Windows NT Schedule service. The Task Scheduler service replaces the Schedule service and is backward-compatible with it. This conversion occurs when the Task Scheduler is installed on Windows NT: for example, installing Internet Explorer 4.0, or upgrading to Windows NT 5. During the setup process, the Task Scheduler installation code searches the registry for jobs created for the AT service, and creates tasks that will accomplish the same operation.

For such converted jobs, the interactive flag is set if the task is intended to be displayed to the user. When this flag is not set, no task items are displayed in the Tasks folder, and no user interface associated with the task is presented to the user when the task is executed.

TASK_FLAG_DELETE_WHEN_DONE
Task will be deleted when there are no more scheduled run times.
TASK_FLAG_DISABLED
Task is disabled. This is useful to temporarily prevent a task from running at the scheduled time(s).
TASK_FLAG_HIDDEN
Task file is hidden. When the task begins execution, it runs in a hidden window.
TASK_FLAG_START_ONLY_IF_IDLE
Task begins only if the computer is not in use at the scheduled start time. Windows 95 only.
TASK_FLAG_KILL_ON_IDLE_END
Task terminates if the computer makes an idle to non-idle transition while the task is running. The computer is not considered idle until the IdleWait triggers' time elapses with no user input. Windows 95 only. For information regarding idle triggers, see Idle Triggers.
TASK_FLAG_DONT_START_IF_ON_BATTERIES
Task does not start if its target computer is running on battery power. Windows 95 only.
TASK_FLAG_KILL_IF_GOING_ON_BATTERIES
Task ends and the associated application quits if the task's target computer switches to battery power. Windows 95 only.
TASK_FLAG_RUN_IF_CONNECTED_TO_INTERNET
Not yet implemented.

See also ITask::GetTaskFlags


ITask::SetWorkingDirectory

HRESULT SetWorkingDirectory(
    LPCWSTR pwszWorkingDirectory
);

Sets the working directory for the task.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pwszWorkingDirectory
LPCWSTR that contains a directory path. The application starts with this directory as the current working directory. To clear the directory, set pwszWorkingDirectory to L"". If the working directory is set to L"", when the application is run, the current directory will be the directory in which the task scheduler service executable, Mstask.exe, resides.

See also ITask::GetWorkingDirectory


ITaskTrigger

Applications use the methods of the ITaskTrigger interface to access and set triggers for a task. Triggers specify task start times, repetition criteria, and other parameters. The following list of methods is organized in vtable order.

ITaskTrigger methods
SetTrigger
GetTrigger
GetTriggerString


ITaskTrigger::GetTrigger

HRESULT GetTrigger(
    PTASK_TRIGGER pTrigger
);

Retrieves the current task trigger.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pTrigger
Address of a TASK_TRIGGER structure that contains the current task trigger. You must set the cbTriggerSize member of the TASK_TRIGGER structure to be the size of the task trigger structure before passing it to this method.

See also ITaskTrigger::SetTrigger


ITaskTrigger::GetTriggerString

HRESULT GetTriggerString(
    LPWSTR * ppwszTrigger
);

Retrieves the current task trigger in the form of a string. This string appears in the Scheduling Agent user interface in a form similar to "At 2PM every day, starting 5/11/97."

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
ppwszTrigger
Address of an LPWSTR that contains the description of the current task trigger. The method that invokes GetTriggerString is responsible for freeing this string using the CoTaskMemFree function.


ITaskTrigger::SetTrigger

HRESULT SetTrigger(
    const PTASK_TRIGGER pTrigger
);

Sets the task trigger values.

  • Returns one of the following values:
    S_OK | The operation was successful.
    E_INVALIDARG | The arguments are not valid.
    E_OUTOFMEMORY | Not enough memory is available.
pTrigger
Address of a TASK_TRIGGER structure containing the values that define the new task trigger.

See also ITaskTrigger::GetTrigger


Structures Structures *
  * Previous Topic: ITaskTrigger::SetTrigger
  * Next Topic: DAILY

Structures

This section describes the Task Scheduler structures.


DAILY

typedef struct _DAILY {
    WORD DaysInterval;
} DAILY;

Defines the interval, in days, between invocations of a task. The TRIGGER_TYPE_UNION union uses an instance of this structure as part of the TASK_TRIGGER structure definition.

DaysInterval
Number of days between invocations of a task.


MONTHLYDATE

typedef struct _MONTHLYDATE {
    DWORD rgfDays;
    WORD rgfMonths;
} MONTHLYDATE;

Defines the day of the month the task will run. The TRIGGER_TYPE_UNION union uses an instance of this structure as part of the TASK_TRIGGER structure definition.

rgfDays
Value that describes the day of the month a task runs. This value is a bit field that specifies the day(s) the task will run. Bit 0 corresponds to the first of the month, bit 1 to the second, and so forth.
rgfMonths
Value that describes the month(s) when the task runs. This value is a combination of the following flags:
TASK_JANUARY | Task will run in January.
TASK_FEBRUARY | Task will run in February.
TASK_MARCH | Task will run in March.
TASK_APRIL | Task will run in April.
TASK_MAY | Task will run in May.
TASK_JUNE | Task will run in June.
TASK_JULY | Task will run in July.
TASK_AUGUST | Task will run in August.
TASK_SEPTEMBER | Task will run in September.
TASK_OCTOBER | Task will run in October.
TASK_NOVEMBER | Task will run in November.
TASK_DECEMBER | Task will run in December.

The following code fragment provides an example of how you can combine these flags. This example would run a task quarterly.

MONTHLYDATE example;
example.rgfDays = 1;
example.rgfMonths = TASK_JANUARY | TASK_APRIL | TASK_JULY | TASK_OCTOBER;


MONTHLYDOW

typedef struct _MONTHLYDOW {
    WORD wWhichWeek;
    WORD rgfDaysOfTheWeek;
    WORD rgfMonths;
} MONTHLYDOW;

(MONTHLY Day Of the Week) Defines the date(s) that the task runs by month, week, and day of week. The TRIGGER_TYPE_UNION union uses an instance of this structure as part of the TASK_TRIGGER structure definition.

wWhichWeek
Value that describes the week of the month when the task runs. This value is exclusive and is one of the following flags:
TASK_FIRST_WEEK | Task will run during the first week of the month.
TASK_SECOND_WEEK | Task will run during the second week of the month.
TASK_THIRD_WEEK | Task will run during the third week of the month.
TASK_FOURTH_WEEK | Task will run during the fourth week of the month.
TASK_LAST_WEEK | Task will run during the last week of the month.
rgfDaysOfTheWeek
Value that describes the day(s) of the week specified in wWhichWeek when the task runs. This value is a combination of the following flags:
TASK_SUNDAY | Task will run on Sunday.
TASK_MONDAY | Task will run on Monday.
TASK_TUESDAY | Task will run on Tuesday.
TASK_WEDNESDAY | Task will run on Wednesday.
TASK_THURSDAY | Task will run on Thursday.
TASK_FRIDAY | Task will run on Friday.
TASK_SATURDAY | Task will run on Saturday.
rgfMonths
Value that describes the month(s) when the task runs. This value is a combination of the following flags:
TASK_JANUARY | Task will run in January.
TASK_FEBRUARY | Task will run in February.
TASK_MARCH | Task will run in March.
TASK_APRIL | Task will run in April.
TASK_MAY | Task will run in May.
TASK_JUNE | Task will run in June.
TASK_JULY | Task will run in July.
TASK_AUGUST | Task will run in August.
TASK_SEPTEMBER | Task will run in September.
TASK_OCTOBER | Task will run in October.
TASK_NOVEMBER | Task will run in November.
TASK_DECEMBER | Task will run in December.

The following code fragment provides an example of how you can combine these flags. This example would run a task on Monday and Friday of the third week of every third month.

MONTHLYDOW example;
example.wWhichWeek = TASK_THIRD_WEEK;
example.rgfDaysOfTheWeek = TASK_FRIDAY | TASK_MONDAY;
example.rgfMonths = TASK_JANUARY | TASK_APRIL | TASK_JULY | TASK_OCTOBER;


TASK_TRIGGER

typedef struct _TASK_TRIGGER {
    WORD cbTriggerSize;
    WORD Reserved1;
    WORD wBeginYear;
    WORD wBeginMonth;
    WORD wBeginDay;
    WORD wEndYear;
    WORD wEndMonth;
    WORD wEndDay;
    WORD wStartHour;
    WORD wStartMinute;
    DWORD MinutesDuration;
    DWORD MinutesInterval;
    DWORD rgFlags;
    TASK_TRIGGER_TYPE TriggerType;
    TRIGGER_TYPE_UNION Type;
    WORD Reserved2;
    WORD wRandomMinutesInterval;
} TASK_TRIGGER, * PTASK_TRIGGER;

Defines the start time, end time, duration, and modification flags for a task.

cbTriggerSize
Size of this structure, in bytes (sizeof(TASK_TRIGGER)).
Reserved1
For internal use only; this value must be zero.
wBeginYear
Year that the task trigger activates. This value must be four digits (1997, not 97).
wBeginMonth
Month of the year in the wBeginYear member that the task trigger activates.
wBeginDay
Day of the month in the wBeginMonth member that the task trigger activates.
wEndYear
Year that the task trigger deactivates. This value must be four digits (1997, not 97).
wEndMonth
Month of the year in the wEndYear member that the task trigger deactivates.
wEndDay
Day of the month in the wEndMonth member that the task trigger deactivates.
wStartHour
Hour of the day the task runs. This value is on a 24-hour clock; hours go from 00 to 23.
wStartMinute
Minute of the hour in the wStartHour member that the task runs.
MinutesDuration
Number of minutes after the task starts that the trigger will remain active. For example, if you start a task at 8:00 A.M. and want to repeatedly start the task until 5:00 P.M., there would be 540 minutes in the duration.
MinutesInterval
Number of minutes between consecutive task executions. This number is counted from the start of the previous task. For example, to run a task every hour from 8:00 A.M. to 5:00 P.M., set this field to 60.
rgFlags
Value that describes the task trigger's behavior. This value is a combination of the following flags:
TASK_TRIGGER_FLAG_HAS_END_DATE
Trigger structure's end date is valid. If this flag is not set, the end date data is ignored and the trigger will be valid indefinitely.
TASK_TRIGGER_FLAG_KILL_AT_DURATION_END
Task will be terminated at the end of the active trigger's lifetime. At the duration end, the scheduling agent first sends a WM_CLOSE message to the associated application. If the application hasn't exited in three minutes, TerminateProcess runs. If more than one instance of a task is running, all instances are terminated.
TASK_TRIGGER_FLAG_DISABLED
Task trigger is inactive.
TriggerType
Value that determines the type of trigger for this task. This value is a member of the TASK_TRIGGER_TYPE enumerated type.
Type
Structure that determines the type of trigger for this task. This structure is a member of the TRIGGER_TYPE_UNION union.
Reserved2
For internal use only; this value must be zero.
wRandomMinutesInterval
Not currently used.


WEEKLY

typedef struct _WEEKLY {
    WORD WeeksInterval;
    WORD rgfDaysOfTheWeek;
} WEEKLY;

Defines the interval, in weeks, between invocations of a task. The TRIGGER_TYPE_UNION union uses an instance of this structure as part of the TASK_TRIGGER structure definition.

WeeksInterval
Number of weeks between invocations of a task.
rgfDaysOfTheWeek
Value that describes the days of the week the task runs. This value is a bit field and is a combination of the following flags:
TASK_SUNDAY | Task will run on Sunday.
TASK_MONDAY | Task will run on Monday.
TASK_TUESDAY | Task will run on Tuesday.
TASK_WEDNESDAY | Task will run on Wednesday.
TASK_THURSDAY | Task will run on Thursday.
TASK_FRIDAY | Task will run on Friday.
TASK_SATURDAY | Task will run on Saturday.

The following code fragment provides an example of how you can combine these flags. This example would run a task on every other Sunday, Wednesday, and Friday.

WEEKLY example;
example.WeeksInterval = 2;
example.rgfDaysOfTheWeek = TASK_SUNDAY | TASK_WEDNESDAY | TASK_FRIDAY;


Unions Unions *
  * Previous Topic: WEEKLY
  * Next Topic: TRIGGER_TYPE_UNION

Unions

This section describes the Task Scheduler union.

TRIGGER_TYPE_UNION


TRIGGER_TYPE_UNION

typedef union _TRIGGER_TYPE_UNION {
    DAILY Daily;
    WEEKLY Weekly;
    MONTHLYDATE MonthlyDate;
    MONTHLYDOW MonthlyDOW;
} TRIGGER_TYPE_UNION;

Defines the task trigger's invocation schedule. This union is part of the TASK_TRIGGER structure.

Daily
Structure that specifies the number of days between invocation of a task. This member is a DAILY structure.
Weekly
Structure that specifies the number of weeks between invocations of a task, and day(s) of the week the task will run. This member is a WEEKLY structure.
MonthlyDate
Structure that specifies the month(s) and day(s) of the month a task will run. This member is a MONTHLYDATE structure.
MonthlyDOW
Structure that specifies the day(s) of the year a task runs by month(s), week of month, and day(s) of week. This member is a MONTHLYDOW structure.


Enumerated Types Enumerated Types *
  * Previous Topic: TRIGGER_TYPE_UNION
  * Next Topic: TASK_TRIGGER_TYPE

Enumerated Types

This section describes the Task Scheduler enumerated types.


TASK_TRIGGER_TYPE

typedef enum _TASK_TRIGGER_TYPE {
    TASK_TIME_TRIGGER_ONCE            = 0,
    TASK_TIME_TRIGGER_DAILY           = 1,
    TASK_TIME_TRIGGER_WEEKLY          = 2,
    TASK_TIME_TRIGGER_MONTHLYDATE     = 3,
    TASK_TIME_TRIGGER_MONTHLYDOW      = 4,
    TASK_EVENT_TRIGGER_ON_IDLE        = 5,
    TASK_EVENT_TRIGGER_AT_SYSTEMSTART = 6,
    TASK_EVENT_TRIGGER_AT_LOGON       = 7
} TASK_TRIGGER_TYPE, *PTASK_TRIGGER_TYPE;

Defines the type of trigger the task will use. This enumerated type is part of the TASK_TRIGGER structure. The trigger type determines when the task will run.

TASK_TIME_TRIGGER_ONCE
Trigger is set to run the task a single time.
TASK_TIME_TRIGGER_DAILY
Trigger is set to run the task on a daily interval.
TASK_TIME_TRIGGER_WEEKLY
Trigger is set to run the task on specific days of the week on a weekly interval.
TASK_TIME_TRIGGER_MONTHLYDATE
Trigger is set to run the task on a specific day(s) of the month.
TASK_TIME_TRIGGER_MONTHLYDOW
Trigger is set to run the task on specific days, weeks, and months.
TASK_EVENT_TRIGGER_ON_IDLE
Trigger is set to run the task when the system becomes idle (Windows 95 only).
TASK_EVENT_TRIGGER_AT_SYSTEMSTART
Trigger is set to run the task at system startup.
TASK_EVENT_TRIGGER_AT_LOGON
Trigger is set to run the task when a user logs on.


TASKPAGE

typedef enum  _TASKPAGE{
    TASKPAGE_TASK     = 0,
    TASKPAGE_SCHEDULE = 1,
    TASKPAGE_SETTINGS = 2
    }TASKPAGE;

Defines characteristics of a task object property. The enumeration values are used in the tpType parameter of the IProvideTaskPage::GetPage function.

TASKPAGE_TASK
Application name.
Parameters to be passed to the application.
Working directory.
Comment information.
Windows NT only Account name and password.
TASK_TRIGGER_FLAG_DISABLED flag.
TASKPAGE_SCHEDULE
Schedule properties for the task object. The user can create and delete task triggers from this page, and edit all of the properties for each of the triggers.
TASKPAGE_SETTINGS
TASK_FLAG_DELETE_WHEN_DONE flag.
MaxRunTime of the task.
Windows 95 only IdleWait.
Windows 95 only TASK_FLAG_START_ONLY_IF_IDLE flag.
Windows 95 only TASK_FLAG_KILL_ON_IDLE_END flag.
Windows 95 only TASK_FLAG_DONT_START_IF_ON_BATTERIES flag.
Windows 95 only TASK_FLAG_KILL_IF_GOING_ON_BATTERIES flag.


Topic Not Found

No matching topic was found. Some possible reasons and remedies are as follows:

  • The file (.chm) that contains the destination topic is not in the expected location.

    Remedy: Rerun the MSDN Library Setup.

  • The file (.chm) that contains the current topic or destination topic is out-of-date and the link is no longer valid.

    Remedy: Install the latest version of the MSDN Library.

  • The MSDN Library CD is not in the CD-ROM drive.

    Remedy: Insert the MSDN Library CD into the CD-ROM drive.