C#查看、建立和刪除系統工作排程器

來源:互聯網
上載者:User
文章目錄
  • Interval屬性
  • StartBoundary屬性
  • ExecutionTimeLimit屬性
  • DisallowStartIfOnBatteries屬性
  • RunOnlyIfIdle屬性

引言:這篇文章能夠教你:

如何建立一個計劃任務程式,每隔一段時間(最短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.設定觸發器

觸發器有很多種,這個在手動建立計劃任務的時候就會發現,如

 

當然最常用的就是按時間觸發,每隔幾天或每個幾個月的觸發器用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”的格式,就是幾小時幾分鐘執行一次,這個值對應的是觸發器對話方塊的“重複任務間隔”如:

設定的值最終都會轉換成分鐘加入到觸發器

官方解釋:

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屬性

此屬性的值對應的是“設定”選項卡的執行期限,如

如果想設定成的效果,就是把複選框勾掉,那就是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屬性

對應的是“條件”選項卡的“僅當電腦空閑時才……”的複選框

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);        }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.