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

http://writeblog.csdn.net/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; } }

Task Scheduler 对win7中任务计划的编程相关推荐

  1. php 计划任务 curl,通过Task Scheduler定时运行调用cURL的PHP脚本 | 学步园

    PHP本身没有定时自动执行的功能,也不支持多线程.但是结合Task Scheduler和cURL,就可以弥补PHP的上述两个缺陷,同时还可以脱离Apache服务器环境,在任意路径下运行PHP脚本. 知 ...

  2. synctoy 自动运行_安排SyncToy在Windows 7中使用Task Scheduler自动运行

    synctoy 自动运行 SyncToy is a great tool to help you keep your files and folders synced between drives a ...

  3. Windows 任务计划程序(task scheduler)介绍

    一.入口 任务计划程序在windows绝大多数版本都是系统自带,可以通过一下入口找到 1.开始--(windows)管理工具 2.服务器管理器--工具(server版) 3.我的电脑(此电脑)--点击 ...

  4. Windows任务计划程序Task Scheduler笔记

    微软文档居然搜不到了 Windows任务计划程序已经存在许多年了,原来在微软的TechNet上有详细的操作介绍的,现在发现网站改版,原来的介绍居然搜索不到了,微软的平台上出现这种事情,也是比较吃惊了. ...

  5. spring 中定时器的 task:executor执行器和调度器task:scheduler

    任务调度器配置:  task:scheduler/@pool-size:调度线程池的大小,调度线程在被调度任务完成前不会空闲  task:scheduled/@cron:cron表达式,注意,若上次任 ...

  6. 无法打开计算机上的event log服务,win 2008 r2无法启动(Task Scheduler和windows eventlog 服务...

    Windows Server 2008 r2: 无法启动(Task Scheduler和windows eventlog 服务) =================================== ...

  7. task文件服务器无法输入,Win10系统无法启动task scheduler服务的解决方法

    Win10无法启动"task scheduler服务"怎么办?task scheduler是一个任务调度程序,用户可以使用task scheduler自动运行计算机任务.在Win1 ...

  8. Spring的任务调度@Scheduled注解——task:scheduler和task:executor的解析

    Spring的任务调度@Scheduled注解--task:scheduler和task:executor的解析 applicationContext 的配置如下: <?xml version= ...

  9. 关于Spring 任务调度之task:scheduler与task:executor配置的详解

    关于Spring 任务调度之task:scheduler与task:executor配置的详解 其实就是Spring定时器中配置文件中一些配置信息,由于笔者自己是头一次使用,有些配置详细不太明白,随即 ...

  10. MicroFocus 监控工具 SiteScope 搭配Task scheduler在远程Windows上执行脚本

    文章目录 SiteScope介绍 配置步骤 1.在远程被监控Windows上准备工作 2.SiteScope端配置 3.设置SiteScope 总结 SiteScope介绍 SiteScope 是HP ...

最新文章

  1. 手把手教你如何进行FileZilla的安装
  2. python ctime源码_Python3基础 getatime getctime getmtime 文件的最近访问 + 属性修改 + 内容修改时间...
  3. 怎么判断ajax返回是否成功,如何判断jquery的ajax请求已经返回
  4. Node.js 基金会和 JS 基金会准备合并,你怎么看?
  5. 运维太忙?那是你还没掌握 Ansible !
  6. Docker运行GUI软件的方法
  7. 洛谷P3270:成绩比较(容斥、组合数学)
  8. 逼自己玩命学了6个多月,吃透了这19个架构视频!分享给你,让你今年进个大厂!...
  9. openstack 开发_2016年OpenStack开发板工作清单
  10. Linux日志管理五大命令详解
  11. Ubuntu 12.04 用户安装Chromium
  12. 多小区下小区上行速率的计算(4)
  13. PDMS二次开发(一)——Hello World for PDMS
  14. oracle12c备份与恢复,Oracle Database12c Oracle RMAN备份与恢复(第4版)
  15. 中小企业监控体系构建实战--案例分享(内附传送门)
  16. EXCEL【数据处理之数据抽取——随机抽样】
  17. 前端性能优化(三)——浏览器九大缓存方法
  18. 解剖RISC-V架构(一)
  19. java 正则校验经纬度格式
  20. SParC: Cross-Domain Semantic Parsing in Context 论文解读

热门文章

  1. Ubuntu 查看硬盘容量
  2. 三阶段最小二乘法 回归分析 3SLS python实现
  3. noi linux 比赛使用哪个编译器,noi linux简介.pdf
  4. ENGLISH-英文进修
  5. 读书笔记_金融数据分析 | 金融数据及其特征
  6. 实木地板被机器人弄成坑_“实木地板”真的好?这些不搞明白,小心被商家坑了...
  7. 从U盘还原完ghost系统,重启就提示bootmgr is missing
  8. Matplotlib之散点图绘制
  9. java中文汉字转英文拼音工具类(无需引用外部pom)
  10. win10内置ubuntu, “指定的网络名不再可用”解决办法