C#查看、创办和删除系统任务计划程序

C#查看、创建和删除系统任务计划程序

引言:这篇文章能够教你:

如何创建一个计划任务程序,每隔一段时间(最短1分钟)就执行一次特定的程序

 

准备工作

复制C:\Windows\System32\taskschd.dll到项目下,添加引用,在属性窗口将“嵌入互操作类型”设置成false

查看系统下所有的任务计划程序

TaskSchedulerClass ts = new TaskSchedulerClass();
            ts.Connect(null, null, null, null);
            ITaskFolder folder = ts.GetFolder("\\");
IRegisteredTaskCollection tasks_exists = folder.GetTasks(1);
                for (int i = 1; i <= tasks_exists.Count; i++)
                {
                    IRegisteredTask t = tasks_exists[i];

                }


注意下标是从1开始的。这样就遍历了所有的计划任务,可以依次查看它们的各个属性。如果你想创建什么样的计划任务,不妨先手动创建一个,再用这段代码查看,这样就知道该设置什么属性了

创建自定义任务计划程序

 

1.实例化对象

//实例化任务对象
            TaskSchedulerClass scheduler = new TaskSchedulerClass();
            scheduler.Connect(null, null, null, null);//连接

注:只有Connect之后才能使用

2.设置基本属性

 

ITaskDefinition task = scheduler.NewTask(0);
                task.RegistrationInfo.Author = "BluceYoung";//创建者
                task.RegistrationInfo.Description = "http://blog.csdn.net/bluceyoung";//描述


3.设置触发器

触发器有很多种,这个在手动创建计划任务的时候就会发现,如下图

 C#查看、创办和删除系统任务计划程序

当然最常用的就是按时间触发,每隔几天或每个几个月的触发器用IDailyTrigger,网上的很多都是以这个为例。我在这里就拿ITimerTrigger做个例子,能实现几分钟就触发一次的效果。

ITimeTrigger tt = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME);
                tt.Repetition.Interval = "PT30M";//循环时间
                   tt.StartBoundary = "2013-01-21T14:27:25";//开始执行时间


Interval属性

就是设置的循环时间,但并不是我们熟悉的毫秒数。它的值需要满足“PT1H1M”的格式,就是几小时几分钟执行一次,这个值对应的是触发器对话框的“重复任务间隔”如下图:

C#查看、创办和删除系统任务计划程序

设置的值最终都会转换成分钟加入到触发器

官方解释:

The amount of time between each restart of the task. The format for this string is P<days>DT<hours>H<minutes>M<seconds>S (for example, "PT5M" is 5 minutes, "PT1H" is 1 hour, and "PT20M" is 20 minutes). The maximum time allowed is 31 days, and the minimum time allowed is 1 minute.

StartBoundary属性

开始执行时间,最常用的格式就是:2005-10-11T13:21:17。官方解释如下:

The date and time must be in the following format: YYYY-MM-DDTHH:MM:SS(+-)HH:MM. The (+-)HH:MM section of the format defines a certain number of hours and minutes ahead or behind Coordinated Universal Time (UTC). For example the date October 11th, 2005 at 1:21:17 with an offset of eight hours behind UTC would be written as 2005-10-11T13:21:17-08:00. If Z is specified for the UTC offset (for example, 2005-10-11T13:21:17Z), then the no offset from UTC will be used. If you do not specify any offset time or Z for the offset (for example, 2005-10-11T13:21:17), then the time zone and daylight saving information that is set on the local computer will be used. When an offset is specified (using hours and minutes or Z), then the time and offset are always used regardless of the time zone and daylight saving settings on the local computer.

4.设置动作

IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
                action.Path = "C:\\Windows\\System32\\calc.exe";


也可以设置发一封邮件,不过还是执行程序的情况多

5.其他设置

task.Settings.ExecutionTimeLimit = "PT0S";
                task.Settings.DisallowStartIfOnBatteries = false;
                task.Settings.RunOnlyIfIdle = false;


ExecutionTimeLimit属性

此属性的值对应的是“设置”选项卡的执行期限,如下图

C#查看、创办和删除系统任务计划程序

如果想设置成如图所示的效果,就是把复选框勾掉,那就是PT0S;

官方解释:

The format for this string is PnYnMnDTnHnMnS, where nY is the number of years, nM is the number of months, nD is the number of days, 'T' is the date/time separator, nH is the number of hours, nM is the number of minutes, and nS is the number of seconds (for example, PT5M specifies 5 minutes and P1M4DT2H5M specifies one month, four days, two hours, and five minutes). A value of PT0S will enable the task to run indefinitely.

DisallowStartIfOnBatteries属性

对应的是“条件”选项卡的“只有在交流电源下才……”的复选框

RunOnlyIfIdle属性

对应的是“条件”选项卡的“仅当计算机空闲时才……”的复选框

如下图

C#查看、创办和删除系统任务计划程序

6.注册任务

IRegisteredTask regTask = folder.RegisterTaskDefinition(
                     "BluceYoungTask",
                     task,
                     (int)_TASK_CREATION.TASK_CREATE,
                     null, //user
                     null, // password
                     _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN,
                     "");
                
                IRunningTask runTask = regTask.Run(null);


其中的BluceYoungTask就是此任务计划程序的名字

_TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN 的意思,貌似是用当前登录的账户去注册任务(所以登录名和密码都是null),而且只有在当前用户登录的情况下才起作用,其他的枚举值没有测试

官方说明参见:http://technet.microsoft.com/zh-cn/library/aa381365

删除任务计划程序

private void DeleteTask(string taskName)
        {
            TaskSchedulerClass ts = new TaskSchedulerClass();
            ts.Connect(null, null, null, null);
            ITaskFolder folder = ts.GetFolder("\\");
            folder.DeleteTask(taskName, 0);
        }