Task Scheduler 对win7中任务计划的编程

本文详细介绍了如何使用COM接口创建、配置、保存任务调度器中的任务,包括创建任务、设置触发器、添加动作等关键步骤,以及如何通过任务调度器实现计划任务的自动化执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://msdn.microsoft.com/en-us/library/aa383614.aspx
http://writeblog.youkuaiyun.com/PostList.aspx

这两个链接很详细的介绍了Task Scheduler。


[cpp]  view plain copy
  1. //  
  2.   
  3. #include "stdafx.h"  
  4. #define _WIN32_DCOM  
  5.   
  6. #include <windows.h>  
  7. #include <atlbase.h>  
  8.   
  9. #include <iostream>  
  10. #include <stdio.h>  
  11. #include <comdef.h>  
  12. //  Include the task header file.  
  13. #include <taskschd.h>  
  14. # pragma comment(lib, "taskschd.lib")  
  15. # pragma comment(lib, "comsupp.lib")  
  16. using namespace std;  
  17.   
  18. int _tmain(int argc, _TCHAR* argv[])  
  19. {  
  20.     //  ------------------------------------------------------  
  21.     //  Initialize COM.  
  22.     LPCWSTR wszTaskName=L"";  
  23.     wstring wstrExecutablePath=L"";  
  24.     if (argc!=3)  
  25.     {  
  26.         printf("输入命令行不正确");  
  27.         return 1;  
  28.     }  
  29.     else  
  30.     {  
  31.         wszTaskName = argv[1];  
  32.         wstrExecutablePath=argv[2];  
  33.     }  
  34.   
  35.     CComPtr<IPrincipal>        principal;  
  36.     //CComPtr<IIdleTrigger>      idleTrigger;   
  37.     HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);  
  38.     if( FAILED(hr) )  
  39.     {  
  40.         printf("/nCoInitializeEx failed: %x", hr );  
  41.         return 1;  
  42.     }  
  43.   
  44.     //  Set general COM security levels.  
  45.     hr = CoInitializeSecurity(  
  46.         NULL,  
  47.         -1,  
  48.         NULL,  
  49.         NULL,  
  50.         RPC_C_AUTHN_LEVEL_PKT_PRIVACY,  
  51.         RPC_C_IMP_LEVEL_IMPERSONATE,  
  52.         NULL,  
  53.         0,  
  54.         NULL);  
  55.   
  56.     if( FAILED(hr) )  
  57.     {  
  58.         printf("/nCoInitializeSecurity failed: %x", hr );  
  59.         CoUninitialize();  
  60.         return 1;  
  61.     }  
  62.     //  ------------------------------------------------------  
  63.     //  Create a name for the task.  
  64.     //LPCWSTR wszTaskName = L"Asus Hotkey Start";  
  65.   
  66.       Get the Windows directory and set the path to Notepad.exe.  
  67.     //wstring wstrExecutablePath = _wgetenv( L"WINDIR");  
  68.     wstrExecutablePath += L"//SYSTEM32//NOTEPAD.EXE";  
  69.   
  70.     //  ------------------------------------------------------  
  71.     //  Create an instance of the Task Service.   
  72.     ITaskService *pService = NULL;  
  73.     hr = CoCreateInstance( CLSID_TaskScheduler,  
  74.         NULL,  
  75.         CLSCTX_INPROC_SERVER,  
  76.         IID_ITaskService,  
  77.         (void**)&pService );    
  78.     if (FAILED(hr))  
  79.     {  
  80.         printf("Failed to create an instance of ITaskService: %x", hr);  
  81.         CoUninitialize();  
  82.         return 1;  
  83.     }  
  84.   
  85.     //  Connect to the task service.  
  86.     hr = pService->Connect(_variant_t(), _variant_t(),  
  87.         _variant_t(), _variant_t());  
  88.     if( FAILED(hr) )  
  89.     {  
  90.         printf("ITaskService::Connect failed: %x", hr );  
  91.         pService->Release();  
  92.         CoUninitialize();  
  93.         return 1;  
  94.     }  
  95.   
  96.     //  ------------------------------------------------------  
  97.     //  Get the pointer to the root task folder.    
  98.     //  This folder will hold the new task that is registered.  
  99.     ITaskFolder *pRootFolder = NULL;  
  100.     hr = pService->GetFolder( _bstr_t( L"//") , &pRootFolder );  
  101.     if( FAILED(hr) )  
  102.     {  
  103.         printf("Cannot get Root Folder pointer: %x", hr );  
  104.         pService->Release();  
  105.         CoUninitialize();  
  106.         return 1;  
  107.     }  
  108.   
  109.     //  If the same task exists, remove it.  
  110.     pRootFolder->DeleteTask( _bstr_t( wszTaskName), 0  );  
  111.   
  112.     //  Create the task builder object to create the task.  
  113.     ITaskDefinition *pTask = NULL;  
  114.     hr = pService->NewTask( 0, &pTask );  
  115.   
  116.     pService->Release();  // COM clean up.  Pointer is no longer used.  
  117.     if (FAILED(hr))  
  118.     {  
  119.         printf("Failed to create a task definition: %x", hr);  
  120.         pRootFolder->Release();  
  121.         CoUninitialize();  
  122.         return 1;  
  123.     }  
  124.   
  125.   
  126.     //  ------------------------------------------------------  
  127.     //  Get the registration info for setting the identification.  
  128.     IRegistrationInfo *pRegInfo= NULL;  
  129.     hr = pTask->get_RegistrationInfo( &pRegInfo );  
  130.     if( FAILED(hr) )  
  131.     {  
  132.         printf("/nCannot get identification pointer: %x", hr );  
  133.         pRootFolder->Release();  
  134.         pTask->Release();  
  135.         CoUninitialize();  
  136.         return 1;  
  137.     }  
  138.   
  139.     hr = pRegInfo->put_Author(L"AsusTek Computer Inc");  
  140.     pRegInfo->Release();  
  141.     if( FAILED(hr) )  
  142.     {  
  143.         printf("/nCannot put identification info: %x", hr );  
  144.         pRootFolder->Release();  
  145.         pTask->Release();  
  146.         CoUninitialize();  
  147.         return 1;  
  148.     }  
  149.   
  150.     //  ------------------------------------------------------  
  151.     //  Create the settings for the task  
  152.     ITaskSettings *pSettings = NULL;  
  153.     hr = pTask->get_Settings( &pSettings );  
  154.     if( FAILED(hr) )  
  155.     {  
  156.         printf("/nCannot get settings pointer: %x", hr );  
  157.         pRootFolder->Release();  
  158.         pTask->Release();  
  159.         CoUninitialize();  
  160.         return 1;  
  161.     }  
  162.   
  163.     pSettings->put_DisallowStartIfOnBatteries(VARIANT_BOOL(FALSE));//auto run even OnBatteries  
  164.     //sets a Boolean value that indicates that the task will be stopped if the computer is going onto batteries.  
  165.     pSettings->put_StopIfGoingOnBatteries(VARIANT_BOOL(FALSE));  
  166.     //sets the amount of time that is allowed to complete the task  
  167.     pSettings->put_ExecutionTimeLimit( CComBSTR(_T("PT0S")));//never auto end  
  168.     //sets the policy that defines how the Task Scheduler deals with multiple instances of the task.  
  169.     pSettings->put_MultipleInstances(TASK_INSTANCES_PARALLEL);  
  170.     //sets a Boolean value that indicates that the task can be started by using either the Run command or the Context menu.  
  171.     pSettings->put_AllowDemandStart(TRUE);  
  172.     //If True, the task can be terminated by using TerminateProcess. If False, the task cannot be terminated by using TerminateProcess.  
  173.     pSettings->put_AllowHardTerminate(TRUE);  
  174.     pSettings->put_RestartCount(5);  
  175.     pSettings->put_RestartInterval(_bstr_t(L"PT1M"));  
  176.   
  177.   
  178.   
  179.     //  Set setting values for the task.   
  180.     hr = pSettings->put_StartWhenAvailable(VARIANT_BOOL(true));  
  181.     pSettings->Release();  
  182.     if( FAILED(hr) )  
  183.     {  
  184.         printf("/nCannot put setting info: %x", hr );  
  185.         pRootFolder->Release();  
  186.         pTask->Release();  
  187.         CoUninitialize();  
  188.         return 1;  
  189.     }  
  190.   
  191.   
  192.     //  ------------------------------------------------------  
  193.     //  Get the trigger collection to insert the boot trigger.  
  194.     ITriggerCollection *pTriggerCollection = NULL;  
  195.     //hr = pTask->get_Triggers( &pTriggerCollection );  
  196.     //if( FAILED(hr) )  
  197.     //{  
  198.     //  printf("/nCannot get trigger collection: %x", hr );  
  199.     //  pRootFolder->Release();  
  200.     //  pTask->Release();  
  201.     //  CoUninitialize();  
  202.     //  return 1;  
  203.     //}  
  204.   
  205.       Add the boot trigger to the task.  
  206.     ITrigger *pTrigger = NULL;  
  207.     //hr = pTriggerCollection->Create( TASK_TRIGGER_BOOT, &pTrigger );   
  208.   
  209.   
  210.     //得到触发器集合      
  211.     hr = pTask->get_Triggers(&pTriggerCollection);  
  212.     if(FAILED(hr))  
  213.     {  
  214.         //return;  
  215.     }  
  216.     //在触发器集合中创建触发器      
  217.     hr = pTriggerCollection->Create(TASK_TRIGGER_LOGON, &pTrigger); //当用户启动时触发  
  218.     if(FAILED(hr))  
  219.     {  
  220.         //return;  
  221.     }  
  222.     pTriggerCollection->Release();  
  223.     if( FAILED(hr) )  
  224.     {  
  225.         printf("/nCannot create the trigger: %x", hr );  
  226.         pRootFolder->Release();  
  227.         pTask->Release();  
  228.         CoUninitialize();  
  229.         return 1;  
  230.     }  
  231.   
  232.     /*IBootTrigger *pBootTrigger = NULL; 
  233.     hr = pTrigger->QueryInterface(  
  234.     IID_IBootTrigger, (void**) &pBootTrigger ); 
  235.     pTrigger->Release(); 
  236.     if( FAILED(hr) ) 
  237.     { 
  238.     printf("/nQueryInterface call failed for IBootTrigger: %x", hr ); 
  239.     pRootFolder->Release(); 
  240.     pTask->Release(); 
  241.     CoUninitialize(); 
  242.     return 1; 
  243.     } 
  244.  
  245.     hr = pBootTrigger->put_Id( _bstr_t( L"Trigger1" ) ); 
  246.     if( FAILED(hr) ) 
  247.     printf("/nCannot put the trigger ID: %x", hr);*/  
  248.   
  249.     /*hr = pBootTrigger->put_Delay( L"PT30S" ); 
  250.     pBootTrigger->Release(); 
  251.     if( FAILED(hr) ) 
  252.     { 
  253.     printf("/nCannot put delay for boot trigger: %x", hr ); 
  254.     pRootFolder->Release(); 
  255.     pTask->Release(); 
  256.     CoUninitialize(); 
  257.     return 1; 
  258.     } */  
  259.   
  260.     //指定最高权限      
  261.     hr = pTask->get_Principal(&principal);  
  262.     if(FAILED(hr))  
  263.     {  
  264.   
  265.     }  
  266.     hr = principal->put_RunLevel(TASK_RUNLEVEL_HIGHEST);  
  267.     if(FAILED(hr))  
  268.     {  
  269.         //return;  
  270.     }  
  271.     //  ------------------------------------------------------  
  272.     //  Add an Action to the task. This task will execute Notepad.exe.       
  273.     IActionCollection *pActionCollection = NULL;  
  274.   
  275.     //  Get the task action collection pointer.  
  276.     hr = pTask->get_Actions( &pActionCollection );  
  277.     if( FAILED(hr) )  
  278.     {  
  279.         printf("/nCannot get Task collection pointer: %x", hr );  
  280.         pRootFolder->Release();  
  281.         pTask->Release();  
  282.         CoUninitialize();  
  283.         return 1;  
  284.     }  
  285.   
  286.     //  Create the action, specifying it as an executable action.  
  287.     IAction *pAction = NULL;  
  288.     hr = pActionCollection->Create( TASK_ACTION_EXEC, &pAction );  
  289.     pActionCollection->Release();  
  290.     if( FAILED(hr) )  
  291.     {  
  292.         printf("/nCannot create the action: %x", hr );  
  293.         pRootFolder->Release();  
  294.         pTask->Release();  
  295.         CoUninitialize();  
  296.         return 1;  
  297.     }  
  298.     IExecAction *pExecAction = NULL;  
  299.     //  QI for the executable task pointer.  
  300.     hr = pAction->QueryInterface(   
  301.         IID_IExecAction, (void**) &pExecAction );  
  302.     pAction->Release();  
  303.     if( FAILED(hr) )  
  304.     {  
  305.         printf("/nQueryInterface call failed for IExecAction: %x", hr );  
  306.         pRootFolder->Release();  
  307.         pTask->Release();  
  308.         CoUninitialize();  
  309.         return 1;  
  310.     }  
  311.   
  312.     //  Set the path of the executable to Notepad.exe.  
  313.     hr = pExecAction->put_Path( _bstr_t( wstrExecutablePath.c_str() ) );   
  314.     pExecAction->Release();   
  315.     if( FAILED(hr) )  
  316.     {  
  317.         printf("/nCannot set path of executable: %x", hr );  
  318.         pRootFolder->Release();  
  319.         pTask->Release();  
  320.         CoUninitialize();  
  321.         return 1;  
  322.     }  
  323.   
  324.   
  325.     //  ------------------------------------------------------  
  326.     //  Save the task in the root folder.  
  327.     IRegisteredTask *pRegisteredTask = NULL;  
  328.     VARIANT varPassword;  
  329.     varPassword.vt = VT_EMPTY;  
  330.     hr = pRootFolder->RegisterTaskDefinition(  
  331.         _bstr_t( wszTaskName ),  
  332.         pTask,  
  333.         TASK_CREATE_OR_UPDATE,  
  334.         _variant_t(L"Builtin//Administrators"),  
  335.         _variant_t(),  
  336.         TASK_LOGON_GROUP,  
  337.         _variant_t(L""),   
  338.         &pRegisteredTask);  
  339.       
  340.     if( FAILED(hr) )  
  341.     {  
  342.         printf("/nError saving the Task : %x", hr );  
  343.         pRootFolder->Release();  
  344.         pTask->Release();  
  345.         CoUninitialize();  
  346.         return 1;  
  347.     }  
  348.   
  349.     printf("/n Success! Task successfully registered. " );  
  350.   
  351.     //  Clean up.  
  352.     pRootFolder->Release();  
  353.     pTask->Release();  
  354.     pRegisteredTask->Release();  
  355.     principal=NULL;  
  356.     CoUninitialize();  
  357.     return 0;  
  358. }  

另一个代码示例:

[cpp]  view plain copy
  1. #include <atlbase.h>  
  2. #include <taskschd.h>  
  3.   
  4. void AddVistaTask() //创建计划任务  
  5. {  
  6.  CComPtr<ITaskService>      service;  
  7.  CComPtr<ITaskFolder>        root_folder;  
  8.  CComPtr<ITaskFolder>        new_folder;  
  9.  CComPtr<IRegisteredTask>    new_task;    
  10.  CComPtr<ITaskDefinition>    task_def;  
  11.  CComPtr<IActionCollection>  actions;  
  12.  CComPtr<IAction>            act1;  
  13.  CComPtr<ITriggerCollection> triggers;  
  14.  CComPtr<ITrigger>          trig1;  
  15.  CComPtr<IPrincipal>        principal;  
  16.   
  17.  //创建实例    
  18.  HRESULT hr = service.CoCreateInstance(__uuidof(TaskScheduler));  
  19.  if(FAILED(hr))  
  20.  {  
  21.   return;  
  22.  }  
  23.  //用默认的用户连接本地计算机  
  24.  hr = service->Connect(CComVariant(),  // local computer  
  25.   CComVariant(),  // current user  
  26.   CComVariant(),  // current domain  
  27.   CComVariant());  // no password  
  28.  if(FAILED(hr))  
  29.  {  
  30.   return;  
  31.  }  
  32.  //得到根任务文件夹    
  33.  hr = service->GetFolder(CComBSTR(L"//"), &root_folder);  
  34.  if(FAILED(hr))  
  35.  {  
  36.   return;  
  37.  }    
  38.  //打开我的任务文件夹    
  39.  hr = root_folder->GetFolder(CComBSTR(L"Feitian//NetRockey4"), &new_folder);  
  40.  if(FAILED(hr)) //如果文件夹不存在,就创建一个  
  41.  {  
  42.   hr = root_folder->CreateFolder(CComBSTR(L"Feitian//NetRockey4"),  
  43.    CComVariant(), &new_folder); //使用默认的安全描述符  
  44.   if(FAILED(hr))  
  45.   {  
  46.    return;  
  47.   }  
  48.  }  
  49.  //找到名字为"RunAtOnce"的任务    
  50.  hr = new_folder->GetTask(CComBSTR(L"RunAtOnce"), &new_task);  
  51.  if(FAILED(hr))  
  52.  {  
  53.   //如果没有找到就创建一个空任务      
  54.   hr = service->NewTask(0, &task_def);  
  55.   if(FAILED(hr))  
  56.   {  
  57.    return;  
  58.   }  
  59.   //得到动作集合      
  60.   hr = task_def->get_Actions(&actions);  
  61.   if(FAILED(hr))  
  62.   {  
  63.    return;  
  64.   }  
  65.   //在动作集合中创建动作      
  66.   hr = actions->Create(TASK_ACTION_EXEC, &act1);  
  67.   if(FAILED(hr))  
  68.   {  
  69.    return;  
  70.   }  
  71.   //向动作里面写入执行程序  
  72.   CComQIPtr<IExecAction> exec_act(act1);      
  73.   WCHAR exe_path[400] = {0};  
  74.   GetModuleFileNameW(0, exe_path, 400);  
  75.   hr = exec_act->put_Path(CComBSTR(exe_path)); //运行本程序  
  76.   if(FAILED(hr))  
  77.   {  
  78.    return;  
  79.   }    
  80.   hr = exec_act->put_Arguments(CComBSTR(L"-systray")); //向动作里面写入执行程序的参数  
  81.   if(FAILED(hr))  
  82.   {  
  83.    return;  
  84.   }  
  85.   //得到触发器集合      
  86.   hr = task_def->get_Triggers(&triggers);  
  87.   if(FAILED(hr))  
  88.   {  
  89.    return;  
  90.   }  
  91.   //在触发器集合中创建触发器      
  92.   hr = triggers->Create(TASK_TRIGGER_LOGON, &trig1); //当用户启动时触发  
  93.   if(FAILED(hr))  
  94.   {  
  95.    return;  
  96.   }  
  97.   //指定最高权限      
  98.   hr = task_def->get_Principal(&principal);  
  99.   if(FAILED(hr))  
  100.   {  
  101.    return;  
  102.   }  
  103.   hr = principal->put_RunLevel(TASK_RUNLEVEL_HIGHEST);  
  104.   if(FAILED(hr))  
  105.   {  
  106.    return;  
  107.   }  
  108.   //把任务添加到目录中去      
  109.   hr = new_folder->RegisterTaskDefinition(CComBSTR(L"RunAtOnce"), //新任务的名称  
  110.    task_def,  
  111.    TASK_CREATE_OR_UPDATE,  
  112.    CComVariant(), // user name  
  113.    CComVariant(), // password  
  114.    TASK_LOGON_INTERACTIVE_TOKEN,  
  115.    CComVariant(), // sddl  
  116.    &new_task);  
  117.   if(FAILED(hr))  
  118.   {  
  119.    return;  
  120.   }  
  121.  }  
  122.  else //如果找到了那个任务,就检查路径对不对  
  123.  {  
  124.  else //如果找到了那个任务,就检查路径对不对  
  125.  {  
  126.   //得到任务定义  
  127.   hr = new_task->get_Definition(&task_def);  
  128.   if(FAILED(hr))  
  129.   {  
  130.    return;  
  131.   }  
  132.   //得到动作集合      
  133.   hr = task_def->get_Actions(&actions);  
  134.   if(FAILED(hr))  
  135.   {  
  136.    return;  
  137.   }  
  138.   //在动作集合中得到动作      
  139.   hr = actions->get_Item(1, &act1);  
  140.   if(FAILED(hr))  
  141.   {  
  142.    return;  
  143.   }  
  144.   //得到动作中的执行程序  
  145.   CComQIPtr<IExecAction> exec_act(act1);    
  146.   CComBSTR exe_path2;  
  147.   hr = exec_act->get_Path(&exe_path2);  
  148.   
  149.   WCHAR exe_path[400] = {0};  
  150.   GetModuleFileNameW(0, exe_path, 400);  
  151.   CComBSTR exe_path3(exe_path);  
  152.   
  153.   //如果路径不同就修改路径  
  154.   if(exe_path3 != exe_path2)  
  155.   {  
  156.    hr = exec_act->put_Path(exe_path3);  
  157.    if(FAILED(hr))  
  158.    {  
  159.     return;  
  160.    }  
  161.    //修改任务  
  162.    hr = new_folder->RegisterTaskDefinition(CComBSTR(L"RunAtOnce"), //新任务的名称  
  163.     task_def,  
  164.     TASK_CREATE_OR_UPDATE,  
  165.     CComVariant(), // user name  
  166.     CComVariant(), // password  
  167.     TASK_LOGON_INTERACTIVE_TOKEN,  
  168.     CComVariant(), // sddl  
  169.     &new_task);  
  170.    if(FAILED(hr))  
  171.    {  
  172.     return;  
  173.    }  
  174.   }    
  175.  }  
  176.  }  
  177.  //移除Vista的计划任务  
  178.  void RemoveVistaTask()  
  179.  {  
  180.   CComPtr<ITaskService>      service;  
  181.   CComPtr<ITaskFolder>        root_folder;  
  182.   CComPtr<ITaskFolder>        new_folder;  
  183.   CComPtr<IRegisteredTask>    new_task;    
  184.   CComPtr<ITaskDefinition>    task_def;  
  185.   CComPtr<IActionCollection>  actions;  
  186.   CComPtr<IAction>            act1;  
  187.   CComPtr<ITriggerCollection> triggers;  
  188.   CComPtr<ITrigger>          trig1;  
  189.   CComPtr<IPrincipal>        principal;  
  190.   
  191.   //创建实例    
  192.   HRESULT hr = service.CoCreateInstance(__uuidof(TaskScheduler));  
  193.   if(FAILED(hr))  
  194.   {  
  195.    return;  
  196.   }  
  197.   //用默认的用户连接本地计算机  
  198.   hr = service->Connect(CComVariant(),  // local computer  
  199.    CComVariant(),  // current user  
  200.    CComVariant(),  // current domain  
  201.    CComVariant());  // no password  
  202.   if(FAILED(hr))  
  203.   {  
  204.    return;  
  205.   }  
  206.   //得到根任务文件夹    
  207.   hr = service->GetFolder(CComBSTR(L"//"), &root_folder);  
  208.   if(FAILED(hr))  
  209.   {  
  210.    return;  
  211.   }    
  212.   //打开我的任务文件夹    
  213.   hr = root_folder->GetFolder(CComBSTR(L"Feitian//NetRockey4"), &new_folder);  
  214.   if(FAILED(hr)) //如果文件夹不存在,就创建一个  
  215.   {  
  216.    return;  
  217.   }  
  218.   //找到任务  
  219.   hr = new_folder->GetTask(CComBSTR(L"RunAtOnce"), &new_task);  
  220.   if(FAILED(hr))  
  221.   {  
  222.    return;  
  223.   }  
  224.   //删除任务  
  225.   hr = new_folder->DeleteTask(CComBSTR(L"RunAtOnce"), 0);  
  226.   if(FAILED(hr))  
  227.   {  
  228.    return;  
  229.   }  
  230.  }  


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值