http://msdn.microsoft.com/en-us/library/aa383614.aspx
http://writeblog.youkuaiyun.com/PostList.aspx
http://writeblog.youkuaiyun.com/PostList.aspx
这两个链接很详细的介绍了Task Scheduler。
- //
- #include "stdafx.h"
- #define _WIN32_DCOM
- #include <windows.h>
- #include <atlbase.h>
- #include <iostream>
- #include <stdio.h>
- #include <comdef.h>
- // Include the task header file.
- #include <taskschd.h>
- # pragma comment(lib, "taskschd.lib")
- # pragma comment(lib, "comsupp.lib")
- using namespace std;
- int _tmain(int argc, _TCHAR* argv[])
- {
- // ------------------------------------------------------
- // Initialize COM.
- LPCWSTR wszTaskName=L"";
- wstring wstrExecutablePath=L"";
- if (argc!=3)
- {
- printf("输入命令行不正确");
- return 1;
- }
- else
- {
- wszTaskName = argv[1];
- wstrExecutablePath=argv[2];
- }
- CComPtr<IPrincipal> principal;
- //CComPtr<IIdleTrigger> idleTrigger;
- HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
- if( FAILED(hr) )
- {
- printf("/nCoInitializeEx failed: %x", hr );
- return 1;
- }
- // Set general COM security levels.
- hr = CoInitializeSecurity(
- NULL,
- -1,
- NULL,
- NULL,
- RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
- RPC_C_IMP_LEVEL_IMPERSONATE,
- NULL,
- 0,
- NULL);
- if( FAILED(hr) )
- {
- printf("/nCoInitializeSecurity failed: %x", hr );
- CoUninitialize();
- return 1;
- }
- // ------------------------------------------------------
- // Create a name for the task.
- //LPCWSTR wszTaskName = L"Asus Hotkey Start";
- Get the Windows directory and set the path to Notepad.exe.
- //wstring wstrExecutablePath = _wgetenv( L"WINDIR");
- wstrExecutablePath += L"//SYSTEM32//NOTEPAD.EXE";
- // ------------------------------------------------------
- // Create an instance of the Task Service.
- ITaskService *pService = NULL;
- hr = CoCreateInstance( CLSID_TaskScheduler,
- NULL,
- CLSCTX_INPROC_SERVER,
- IID_ITaskService,
- (void**)&pService );
- if (FAILED(hr))
- {
- printf("Failed to create an instance of ITaskService: %x", hr);
- CoUninitialize();
- return 1;
- }
- // Connect to the task service.
- hr = pService->Connect(_variant_t(), _variant_t(),
- _variant_t(), _variant_t());
- if( FAILED(hr) )
- {
- printf("ITaskService::Connect failed: %x", hr );
- pService->Release();
- CoUninitialize();
- return 1;
- }
- // ------------------------------------------------------
- // Get the pointer to the root task folder.
- // This folder will hold the new task that is registered.
- ITaskFolder *pRootFolder = NULL;
- hr = pService->GetFolder( _bstr_t( L"//") , &pRootFolder );
- if( FAILED(hr) )
- {
- printf("Cannot get Root Folder pointer: %x", hr );
- pService->Release();
- CoUninitialize();
- return 1;
- }
- // If the same task exists, remove it.
- pRootFolder->DeleteTask( _bstr_t( wszTaskName), 0 );
- // Create the task builder object to create the task.
- ITaskDefinition *pTask = NULL;
- hr = pService->NewTask( 0, &pTask );
- pService->Release(); // COM clean up. Pointer is no longer used.
- if (FAILED(hr))
- {
- printf("Failed to create a task definition: %x", hr);
- pRootFolder->Release();
- CoUninitialize();
- return 1;
- }
- // ------------------------------------------------------
- // Get the registration info for setting the identification.
- IRegistrationInfo *pRegInfo= NULL;
- hr = pTask->get_RegistrationInfo( &pRegInfo );
- if( FAILED(hr) )
- {
- printf("/nCannot get identification pointer: %x", hr );
- pRootFolder->Release();
- pTask->Release();
- CoUninitialize();
- return 1;
- }
- hr = pRegInfo->put_Author(L"AsusTek Computer Inc");
- pRegInfo->Release();
- if( FAILED(hr) )
- {
- printf("/nCannot put identification info: %x", hr );
- pRootFolder->Release();
- pTask->Release();
- CoUninitialize();
- return 1;
- }
- // ------------------------------------------------------
- // Create the settings for the task
- ITaskSettings *pSettings = NULL;
- hr = pTask->get_Settings( &pSettings );
- if( FAILED(hr) )
- {
- printf("/nCannot get settings pointer: %x", hr );
- pRootFolder->Release();
- pTask->Release();
- CoUninitialize();
- return 1;
- }
- pSettings->put_DisallowStartIfOnBatteries(VARIANT_BOOL(FALSE));//auto run even OnBatteries
- //sets a Boolean value that indicates that the task will be stopped if the computer is going onto batteries.
- pSettings->put_StopIfGoingOnBatteries(VARIANT_BOOL(FALSE));
- //sets the amount of time that is allowed to complete the task
- pSettings->put_ExecutionTimeLimit( CComBSTR(_T("PT0S")));//never auto end
- //sets the policy that defines how the Task Scheduler deals with multiple instances of the task.
- pSettings->put_MultipleInstances(TASK_INSTANCES_PARALLEL);
- //sets a Boolean value that indicates that the task can be started by using either the Run command or the Context menu.
- pSettings->put_AllowDemandStart(TRUE);
- //If True, the task can be terminated by using TerminateProcess. If False, the task cannot be terminated by using TerminateProcess.
- pSettings->put_AllowHardTerminate(TRUE);
- pSettings->put_RestartCount(5);
- pSettings->put_RestartInterval(_bstr_t(L"PT1M"));
- // Set setting values for the task.
- hr = pSettings->put_StartWhenAvailable(VARIANT_BOOL(true));
- pSettings->Release();
- if( FAILED(hr) )
- {
- printf("/nCannot put setting info: %x", hr );
- pRootFolder->Release();
- pTask->Release();
- CoUninitialize();
- return 1;
- }
- // ------------------------------------------------------
- // Get the trigger collection to insert the boot trigger.
- ITriggerCollection *pTriggerCollection = NULL;
- //hr = pTask->get_Triggers( &pTriggerCollection );
- //if( FAILED(hr) )
- //{
- // printf("/nCannot get trigger collection: %x", hr );
- // pRootFolder->Release();
- // pTask->Release();
- // CoUninitialize();
- // return 1;
- //}
- Add the boot trigger to the task.
- ITrigger *pTrigger = NULL;
- //hr = pTriggerCollection->Create( TASK_TRIGGER_BOOT, &pTrigger );
- //得到触发器集合
- hr = pTask->get_Triggers(&pTriggerCollection);
- if(FAILED(hr))
- {
- //return;
- }
- //在触发器集合中创建触发器
- hr = pTriggerCollection->Create(TASK_TRIGGER_LOGON, &pTrigger); //当用户启动时触发
- if(FAILED(hr))
- {
- //return;
- }
- pTriggerCollection->Release();
- if( FAILED(hr) )
- {
- printf("/nCannot create the trigger: %x", hr );
- pRootFolder->Release();
- pTask->Release();
- CoUninitialize();
- return 1;
- }
- /*IBootTrigger *pBootTrigger = NULL;
- hr = pTrigger->QueryInterface(
- IID_IBootTrigger, (void**) &pBootTrigger );
- pTrigger->Release();
- if( FAILED(hr) )
- {
- printf("/nQueryInterface call failed for IBootTrigger: %x", hr );
- pRootFolder->Release();
- pTask->Release();
- CoUninitialize();
- return 1;
- }
- hr = pBootTrigger->put_Id( _bstr_t( L"Trigger1" ) );
- if( FAILED(hr) )
- printf("/nCannot put the trigger ID: %x", hr);*/
- /*hr = pBootTrigger->put_Delay( L"PT30S" );
- pBootTrigger->Release();
- if( FAILED(hr) )
- {
- printf("/nCannot put delay for boot trigger: %x", hr );
- pRootFolder->Release();
- pTask->Release();
- CoUninitialize();
- return 1;
- } */
- //指定最高权限
- hr = pTask->get_Principal(&principal);
- if(FAILED(hr))
- {
- }
- hr = principal->put_RunLevel(TASK_RUNLEVEL_HIGHEST);
- if(FAILED(hr))
- {
- //return;
- }
- // ------------------------------------------------------
- // Add an Action to the task. This task will execute Notepad.exe.
- IActionCollection *pActionCollection = NULL;
- // Get the task action collection pointer.
- hr = pTask->get_Actions( &pActionCollection );
- if( FAILED(hr) )
- {
- printf("/nCannot get Task collection pointer: %x", hr );
- pRootFolder->Release();
- pTask->Release();
- CoUninitialize();
- return 1;
- }
- // Create the action, specifying it as an executable action.
- IAction *pAction = NULL;
- hr = pActionCollection->Create( TASK_ACTION_EXEC, &pAction );
- pActionCollection->Release();
- if( FAILED(hr) )
- {
- printf("/nCannot create the action: %x", hr );
- pRootFolder->Release();
- pTask->Release();
- CoUninitialize();
- return 1;
- }
- IExecAction *pExecAction = NULL;
- // QI for the executable task pointer.
- hr = pAction->QueryInterface(
- IID_IExecAction, (void**) &pExecAction );
- pAction->Release();
- if( FAILED(hr) )
- {
- printf("/nQueryInterface call failed for IExecAction: %x", hr );
- pRootFolder->Release();
- pTask->Release();
- CoUninitialize();
- return 1;
- }
- // Set the path of the executable to Notepad.exe.
- hr = pExecAction->put_Path( _bstr_t( wstrExecutablePath.c_str() ) );
- pExecAction->Release();
- if( FAILED(hr) )
- {
- printf("/nCannot set path of executable: %x", hr );
- pRootFolder->Release();
- pTask->Release();
- CoUninitialize();
- return 1;
- }
- // ------------------------------------------------------
- // Save the task in the root folder.
- IRegisteredTask *pRegisteredTask = NULL;
- VARIANT varPassword;
- varPassword.vt = VT_EMPTY;
- hr = pRootFolder->RegisterTaskDefinition(
- _bstr_t( wszTaskName ),
- pTask,
- TASK_CREATE_OR_UPDATE,
- _variant_t(L"Builtin//Administrators"),
- _variant_t(),
- TASK_LOGON_GROUP,
- _variant_t(L""),
- &pRegisteredTask);
- if( FAILED(hr) )
- {
- printf("/nError saving the Task : %x", hr );
- pRootFolder->Release();
- pTask->Release();
- CoUninitialize();
- return 1;
- }
- printf("/n Success! Task successfully registered. " );
- // Clean up.
- pRootFolder->Release();
- pTask->Release();
- pRegisteredTask->Release();
- principal=NULL;
- CoUninitialize();
- return 0;
- }
另一个代码示例:
- #include <atlbase.h>
- #include <taskschd.h>
- void AddVistaTask() //创建计划任务
- {
- CComPtr<ITaskService> service;
- CComPtr<ITaskFolder> root_folder;
- CComPtr<ITaskFolder> new_folder;
- CComPtr<IRegisteredTask> new_task;
- CComPtr<ITaskDefinition> task_def;
- CComPtr<IActionCollection> actions;
- CComPtr<IAction> act1;
- CComPtr<ITriggerCollection> triggers;
- CComPtr<ITrigger> trig1;
- CComPtr<IPrincipal> principal;
- //创建实例
- HRESULT hr = service.CoCreateInstance(__uuidof(TaskScheduler));
- if(FAILED(hr))
- {
- return;
- }
- //用默认的用户连接本地计算机
- hr = service->Connect(CComVariant(), // local computer
- CComVariant(), // current user
- CComVariant(), // current domain
- CComVariant()); // no password
- if(FAILED(hr))
- {
- return;
- }
- //得到根任务文件夹
- hr = service->GetFolder(CComBSTR(L"//"), &root_folder);
- if(FAILED(hr))
- {
- return;
- }
- //打开我的任务文件夹
- hr = root_folder->GetFolder(CComBSTR(L"Feitian//NetRockey4"), &new_folder);
- if(FAILED(hr)) //如果文件夹不存在,就创建一个
- {
- hr = root_folder->CreateFolder(CComBSTR(L"Feitian//NetRockey4"),
- CComVariant(), &new_folder); //使用默认的安全描述符
- if(FAILED(hr))
- {
- return;
- }
- }
- //找到名字为"RunAtOnce"的任务
- hr = new_folder->GetTask(CComBSTR(L"RunAtOnce"), &new_task);
- if(FAILED(hr))
- {
- //如果没有找到就创建一个空任务
- hr = service->NewTask(0, &task_def);
- if(FAILED(hr))
- {
- return;
- }
- //得到动作集合
- hr = task_def->get_Actions(&actions);
- if(FAILED(hr))
- {
- return;
- }
- //在动作集合中创建动作
- hr = actions->Create(TASK_ACTION_EXEC, &act1);
- if(FAILED(hr))
- {
- return;
- }
- //向动作里面写入执行程序
- CComQIPtr<IExecAction> exec_act(act1);
- WCHAR exe_path[400] = {0};
- GetModuleFileNameW(0, exe_path, 400);
- hr = exec_act->put_Path(CComBSTR(exe_path)); //运行本程序
- if(FAILED(hr))
- {
- return;
- }
- hr = exec_act->put_Arguments(CComBSTR(L"-systray")); //向动作里面写入执行程序的参数
- if(FAILED(hr))
- {
- return;
- }
- //得到触发器集合
- hr = task_def->get_Triggers(&triggers);
- if(FAILED(hr))
- {
- return;
- }
- //在触发器集合中创建触发器
- hr = triggers->Create(TASK_TRIGGER_LOGON, &trig1); //当用户启动时触发
- if(FAILED(hr))
- {
- return;
- }
- //指定最高权限
- hr = task_def->get_Principal(&principal);
- if(FAILED(hr))
- {
- return;
- }
- hr = principal->put_RunLevel(TASK_RUNLEVEL_HIGHEST);
- if(FAILED(hr))
- {
- return;
- }
- //把任务添加到目录中去
- hr = new_folder->RegisterTaskDefinition(CComBSTR(L"RunAtOnce"), //新任务的名称
- task_def,
- TASK_CREATE_OR_UPDATE,
- CComVariant(), // user name
- CComVariant(), // password
- TASK_LOGON_INTERACTIVE_TOKEN,
- CComVariant(), // sddl
- &new_task);
- if(FAILED(hr))
- {
- return;
- }
- }
- else //如果找到了那个任务,就检查路径对不对
- {
- else //如果找到了那个任务,就检查路径对不对
- {
- //得到任务定义
- hr = new_task->get_Definition(&task_def);
- if(FAILED(hr))
- {
- return;
- }
- //得到动作集合
- hr = task_def->get_Actions(&actions);
- if(FAILED(hr))
- {
- return;
- }
- //在动作集合中得到动作
- hr = actions->get_Item(1, &act1);
- if(FAILED(hr))
- {
- return;
- }
- //得到动作中的执行程序
- CComQIPtr<IExecAction> exec_act(act1);
- CComBSTR exe_path2;
- hr = exec_act->get_Path(&exe_path2);
- WCHAR exe_path[400] = {0};
- GetModuleFileNameW(0, exe_path, 400);
- CComBSTR exe_path3(exe_path);
- //如果路径不同就修改路径
- if(exe_path3 != exe_path2)
- {
- hr = exec_act->put_Path(exe_path3);
- if(FAILED(hr))
- {
- return;
- }
- //修改任务
- hr = new_folder->RegisterTaskDefinition(CComBSTR(L"RunAtOnce"), //新任务的名称
- task_def,
- TASK_CREATE_OR_UPDATE,
- CComVariant(), // user name
- CComVariant(), // password
- TASK_LOGON_INTERACTIVE_TOKEN,
- CComVariant(), // sddl
- &new_task);
- if(FAILED(hr))
- {
- return;
- }
- }
- }
- }
- //移除Vista的计划任务
- void RemoveVistaTask()
- {
- CComPtr<ITaskService> service;
- CComPtr<ITaskFolder> root_folder;
- CComPtr<ITaskFolder> new_folder;
- CComPtr<IRegisteredTask> new_task;
- CComPtr<ITaskDefinition> task_def;
- CComPtr<IActionCollection> actions;
- CComPtr<IAction> act1;
- CComPtr<ITriggerCollection> triggers;
- CComPtr<ITrigger> trig1;
- CComPtr<IPrincipal> principal;
- //创建实例
- HRESULT hr = service.CoCreateInstance(__uuidof(TaskScheduler));
- if(FAILED(hr))
- {
- return;
- }
- //用默认的用户连接本地计算机
- hr = service->Connect(CComVariant(), // local computer
- CComVariant(), // current user
- CComVariant(), // current domain
- CComVariant()); // no password
- if(FAILED(hr))
- {
- return;
- }
- //得到根任务文件夹
- hr = service->GetFolder(CComBSTR(L"//"), &root_folder);
- if(FAILED(hr))
- {
- return;
- }
- //打开我的任务文件夹
- hr = root_folder->GetFolder(CComBSTR(L"Feitian//NetRockey4"), &new_folder);
- if(FAILED(hr)) //如果文件夹不存在,就创建一个
- {
- return;
- }
- //找到任务
- hr = new_folder->GetTask(CComBSTR(L"RunAtOnce"), &new_task);
- if(FAILED(hr))
- {
- return;
- }
- //删除任务
- hr = new_folder->DeleteTask(CComBSTR(L"RunAtOnce"), 0);
- if(FAILED(hr))
- {
- return;
- }
- }