- Notifications
You must be signed in to change notification settings - Fork 202
Examples
David Hall edited this page Jul 12, 2019
·
3 revisions
You can go to these pages for more sample code:
Below are some examples of how to use most of the functions of the library:
- Using the editor
- Simple task creation
- Get and delete a task
- Enumerate all tasks
- Complex example
- XML example
- Fluent example
- Task history example
On all these examples, if you get an error on ambiguous references for 'Action', please preface it with 'Microsoft.Win32.TaskScheduler.Action'.
// Create a new taskconststringtaskName="Test";Taskt=TaskService.Instance.AddTask(taskName,newTimeTrigger(){StartBoundary=DateTime.Now+TimeSpan.FromHours(1),Enabled=false},newExecAction("notepad.exe","c:\\test.log","C:\\"));// Edit task and re-register if user clicks OkTaskEditDialogeditorForm=newTaskEditDialog();editorForm.Editable=true;editorForm.RegisterTaskOnAccept=true;editorForm.Initialize(t);// ** The four lines above can be replaced by using the full constructor// TaskEditDialog editorForm = new TaskEditDialog(t, true, true);editorForm.ShowDialog();// Create a new task definition and assign propertiesTaskDefinitiontd=TaskService.Instance.NewTask();td.RegistrationInfo.Description="Does something";td.Principal.LogonType=TaskLogonType.InteractiveToken;// Add a trigger that will fire the task at this time every other dayDailyTriggerdt=(DailyTrigger)td.Triggers.Add(newDailyTrigger(2));dt.Repetition.Duration=TimeSpan.FromHours(4);dt.Repetition.Interval=TimeSpan.FromHours(1);// Add a trigger that will fire every week on Fridaytd.Triggers.Add(newWeeklyTrigger{StartBoundary=DateTime.Today+TimeSpan.FromHours(2),DaysOfWeek=DaysOfTheWeek.Friday});// Add an action that will launch Notepad whenever the trigger firestd.Actions.Add(newExecAction("notepad.exe","c:\\test.log",null));// Register the task in the root folderconststringtaskName="Test";TaskService.Instance.RootFolder.RegisterTaskDefinition(taskName,td);voidGetAndDeleteTask(taskName){// Retrieve the task, change the trigger and re-register it.// A taskName by itself assumes the root folder (e.g. "MyTask")// A taskName can include folders (e.g. "MyFolder\MySubFolder\MyTask")Taskt=ts.GetTask(taskName);if(t==null)return;t.Definition.Triggers[0](0).StartBoundary=DateTime.Today+TimeSpan.FromDays(7);t.RegisterChanges();// Check to make sure account privileges allow task deletionvaridentity=WindowsIdentity.GetCurrent();varprincipal=newWindowsPrincipal(identity);if(!principal.IsInRole(WindowsBuiltInRole.Administrator))thrownewException($"Cannot delete task with your current identity '{identity.Name}' permissions level."+"You likely need to run this application 'as administrator' even if you are using an administrator account.");// Remove the task we just createdts.RootFolder.DeleteTask(taskName);}voidEnumAllTasks(){EnumFolderTasks(TaskService.Instance.RootFolder);}voidEnumFolderTasks(TaskFolderfld){foreach(Tasktaskinfld.Tasks)ActOnTask(task);foreach(TaskFoldersfldinfld.SubFolders)EnumFolderTasks(sfld);}voidActOnTask(Taskt){// Do something interesting here}stringuser=System.Security.Principal.WindowsIdentity.GetCurrent().Name;boolpreWin7=true;// Display version and server stateVersionver=TaskService.Instance.HighestSupportedVersion;boolnewVer=(ver>=newVersion(1,2));Console.WriteLine("Highest version: "+ver);Console.WriteLine("Server: {0} ({1})",TaskService.Instance.TargetServer,TaskService.Instance.Connected?"Connected":"Disconnected");// Output all of the running tasksConsole.WriteLine("Running tasks:");foreach(RunningTaskrtinTaskService.Instance.GetRunningTasks(true)){if(rt!=null){Console.WriteLine("+ {0}, {1} ({2})",rt.Name,rt.Path,rt.State);if(ver.Minor>0)Console.WriteLine(" Current Action: "+rt.CurrentAction);}}// Output all the tasks in the root folder with their triggers and actionsTaskFoldertf=TaskService.Instance.RootFolder;Console.WriteLine("\nRoot folder tasks ({0}):",tf.Tasks.Count);foreach(Tasktintf.Tasks){try{Console.WriteLine("+ {0}, {1} ({2})",t.Name,t.Definition.RegistrationInfo.Author,t.State);foreach(Triggertrgint.Definition.Triggers)Console.WriteLine(" + {0}",trg);foreach(Actionactint.Definition.Actions)Console.WriteLine(" = {0}",act);}catch{}}// Output an enumeration of all folders under the rootConsole.WriteLine("\n******Checking folder enum******");TaskFolderCollectiontfs=tf.SubFolders;if(tfs.Count>0){Console.WriteLine("\nSub folders:");try{foreach(TaskFoldersfintfs)Console.WriteLine("+ {0}",sf.Path);}catch(Exceptionex){Console.WriteLine(ex.ToString());}}// Display information about the Microsoft folderif(newVer){Console.WriteLine("\n******Checking folder retrieval******");try{TaskFoldersub=tf.SubFolders["Microsoft"](_Microsoft_);Console.WriteLine("\nSubfolder path: "+sub.Path);}catch(NotSupportedException){}catch(Exceptionex){Console.WriteLine(ex.ToString());}}Console.WriteLine("\n******Checking task creation******");try{// Create a new task definition and assign propertiesTaskDefinitiontd=TaskService.Instance.NewTask();td.Data="Your data";td.Principal.UserId=user;td.Principal.LogonType=TaskLogonType.InteractiveToken;td.RegistrationInfo.Author="dahall";td.RegistrationInfo.Description="Does something";td.RegistrationInfo.Documentation="Don't pretend this is real.";td.Settings.DisallowStartIfOnBatteries=true;td.Settings.Enabled=false;td.Settings.ExecutionTimeLimit=TimeSpan.FromHours(2);td.Settings.Hidden=false;td.Settings.IdleSettings.IdleDuration=TimeSpan.FromMinutes(20);td.Settings.IdleSettings.RestartOnIdle=false;td.Settings.IdleSettings.StopOnIdleEnd=false;td.Settings.IdleSettings.WaitTimeout=TimeSpan.FromMinutes(10);td.Settings.Priority=System.Diagnostics.ProcessPriorityClass.Normal;td.Settings.RunOnlyIfIdle=false;td.Settings.RunOnlyIfNetworkAvailable=false;td.Settings.StopIfGoingOnBatteries=true;if(newVer){td.Principal.RunLevel=TaskRunLevel.Highest;//.LUA;td.RegistrationInfo.Source="Test App";td.RegistrationInfo.URI=newUri("test://app");td.RegistrationInfo.Version=newVersion(0,9);td.Settings.AllowDemandStart=true;td.Settings.AllowHardTerminate=true;td.Settings.Compatibility=TaskCompatibility.V2;td.Settings.DeleteExpiredTaskAfter=TimeSpan.FromMinutes(1);td.Settings.MultipleInstances=TaskInstancesPolicy.StopExisting;td.Settings.StartWhenAvailable=true;td.Settings.WakeToRun=false;td.Settings.RestartCount=5;td.Settings.RestartInterval=TimeSpan.FromSeconds(100);}if(preWin7){// Create a trigger that fires 5 minutes after the system is bootedBootTriggerbTrigger=(BootTrigger)td.Triggers.Add(newBootTrigger{Enabled=false});if(newVer)bTrigger.Delay=TimeSpan.FromMinutes(5);}// Create a trigger that fires every other day randomly between 6:00 and 8:00 a.m.DailyTriggerdTrigger=(DailyTrigger)td.Triggers.Add(newDailyTrigger());dTrigger.StartBoundary=DateTime.Today+TimeSpan.FromHours(6);dTrigger.DaysInterval=2;if(newVer)dTrigger.RandomDelay=TimeSpan.FromHours(2);if(newVer){if(preWin7){// Create a trigger that will fire on a system security eventEventTriggereTrigger=(EventTrigger)td.Triggers.Add(newEventTrigger());eTrigger.SetBasic("Security","VSSAudit",25);eTrigger.ValueQueries.Add("Name","Value");}// Create a trigger that fires 5 minutes after this task is registeredtd.Triggers.Add(newRegistrationTrigger{Delay=TimeSpan.FromMinutes(5)});if(preWin7){// Create triggers that fire after various system states are changedtd.Triggers.Add(newSessionStateChangeTrigger{StateChange=TaskSessionStateChangeType.ConsoleConnect,UserId=user});td.Triggers.Add(newSessionStateChangeTrigger{StateChange=TaskSessionStateChangeType.ConsoleDisconnect});td.Triggers.Add(newSessionStateChangeTrigger{StateChange=TaskSessionStateChangeType.RemoteConnect});td.Triggers.Add(newSessionStateChangeTrigger{StateChange=TaskSessionStateChangeType.RemoteDisconnect});td.Triggers.Add(newSessionStateChangeTrigger{StateChange=TaskSessionStateChangeType.SessionLock,UserId=user});td.Triggers.Add(newSessionStateChangeTrigger{StateChange=TaskSessionStateChangeType.SessionUnlock});}}// Create a trigger that fires when the system is idletd.Triggers.Add(newIdleTrigger());// Create a trigger that fires 15 minutes after the current user logs on and// then every 1000 seconds after thatLogonTriggerlTrigger=(LogonTrigger)td.Triggers.Add(newLogonTrigger());if(newVer){lTrigger.Delay=TimeSpan.FromMinutes(15);lTrigger.UserId=user;lTrigger.Repetition.Interval=TimeSpan.FromSeconds(1000);}// Create a trigger that fires on the 3rd, 6th, 10th, 18th, and last days of// July and November and stops triggering 90 days from nowMonthlyTriggermTrigger=(MonthlyTrigger)td.Triggers.Add(newMonthlyTrigger());mTrigger.DaysOfMonth=newint[](){3,6,10,18};mTrigger.MonthsOfYear=MonthsOfTheYear.July|MonthsOfTheYear.November;if(newVer)mTrigger.RunOnLastDayOfMonth=true;mTrigger.EndBoundary=DateTime.Today+TimeSpan.FromDays(90);// Create a trigger that fires every day of the first and last week of// December and JanuaryMonthlyDOWTriggermdTrigger=(MonthlyDOWTrigger)td.Triggers.Add(newMonthlyDOWTrigger());mdTrigger.DaysOfWeek=DaysOfTheWeek.AllDays;mdTrigger.MonthsOfYear=MonthsOfTheYear.January|MonthsOfTheYear.December;if(newVer)mdTrigger.RunOnLastWeekOfMonth=true;mdTrigger.WeeksOfMonth=WhichWeek.FirstWeek;// Create a trigger that fires 1 minute from now and then every 15 minutes for the// next 7 days.TimeTriggertTrigger=(TimeTrigger)td.Triggers.Add(newTimeTrigger());tTrigger.StartBoundary=DateTime.Now+TimeSpan.FromMinutes(1);tTrigger.EndBoundary=DateTime.Today+TimeSpan.FromDays(7);if(newVer)tTrigger.ExecutionTimeLimit=TimeSpan.FromSeconds(15);if(newVer)tTrigger.Id="Time test";tTrigger.Repetition.Duration=TimeSpan.FromMinutes(20);tTrigger.Repetition.Interval=TimeSpan.FromMinutes(15);tTrigger.Repetition.StopAtDurationEnd=true;// Create a trigger that fires every third week on MondayWeeklyTriggerwTrigger=(WeeklyTrigger)td.Triggers.Add(newWeeklyTrigger());wTrigger.DaysOfWeek=DaysOfTheWeek.Monday;wTrigger.WeeksInterval=3;// Create an action which opens a log file in notepadtd.Actions.Add(newExecAction("notepad.exe","c:\\test.log",null));if(newVer){// Create an action which shows a message to the interactive usertd.Actions.Add(newShowMessageAction("Running Notepad","Info"));// Create an action which sends an emailtd.Actions.Add(newEmailAction("Testing","dahall@codeplex.com","user@test.com","You've got mail.","mail.myisp.com"));// Create an action which loads a COM object and calls the ITaskHandler// interfacetd.Actions.Add(newComHandlerAction(newGuid("CE7D4428-8A77-4c5d-8A13-5CAB5D1EC734"),string.Empty));}// Register the task definition (saves it) in the security context of the// interactive usertf.RegisterTaskDefinition("Test",td,TaskCreation.CreateOrUpdate,null,null,TaskLogonType.InteractiveToken,null);}catch(Exceptionex){Console.WriteLine(ex.ToString());}// Display information about the newly created taskTaskrunningTask=tf.Tasks["Test"](_Test_);Console.WriteLine("\nNew task will run at "+runningTask.NextRunTime);Console.WriteLine("\nNew task triggers:");for(inti=0;i<runningTask.Definition.Triggers.Count;i++)Console.WriteLine(" {0}: {1}",i,runningTask.Definition.Triggers[i](i));Console.WriteLine("\nNew task actions:");for(inti=0;i<runningTask.Definition.Actions.Count;i++)Console.WriteLine(" {0}: {1}",i,runningTask.Definition.Actions[i](i));// Remove the task we just created since this was just a testtf.DeleteTask("Test");Tasks can be saved or created from scratch in XML and then registered directly as an alternative to setting individual properties.
// Save a Task's XML to a filestringxml=TaskService.Instance.GetTask("\\Temp").Xml;System.IO.File.WriteAllText("localfile.xml",td.XmlText,System.Text.Encoding.Unicode);// Create a Task using XML with user informationTaskService.Instance.RootFolder.RegisterTask("NewTask1",xml,TaskCreation.Create,"SYSTEM",null,TaskLogonType.SystemAccount);// Create a Task directly from a fileTaskService.Instance.RootFolder.ImportTask("NewTask2","localfile.xml");// Load an XML file for editing, change a property, and registerTaskDefintiontd=TaskService.Instance.NewTask();td.XmlText=System.IO.File.ReadAllText("localfile.xml");td.Settings.AllowDemandStart=true;TaskService.Instance.RootFolder.RegisterTaskDefinition("NewTask3",td);The library also exposes a Fluent syntax for accomplishing most functions. Below are a number of examples.
TaskService.Instance.Execute("notepad.exe").WithArguments(@"c:\temp\music.txt").Once().Starting(2013,11,11,11,0,0).RepeatingEvery(TimeSpan.FromMinutes(5)).AsTask("Test");TaskService.Instance.Execute("notepad.exe").Every(2).Days().Starting("12/25/2013 7:00pm").AsTask("Test");TaskService.Instance.Execute("notepad.exe").Every(3).Weeks().AsTask("Test");TaskService.Instance.Execute("notepad.exe").OnAll(DaysOfTheWeek.Monday).In(WhichWeek.FirstWeek).Of(MonthsOfTheYear.January).AsTask("Test");TaskService.Instance.Execute("notepad.exe").InTheMonthOf(MonthsOfTheYear.January).OnTheDays(1,3,5).AsTask("Test");TaskService.Instance.Execute("notepad.exe").OnBoot().AsTask("Test");TaskService.Instance.Execute("notepad.exe").OnIdle().AsTask("Test");TaskService.Instance.Execute("notepad.exe").OnStateChange(TaskSessionStateChangeType.ConsoleConnect).AsTask("Test");TaskService.Instance.Execute("notepad.exe").AtLogonOf("AMERICAS\\dahall").AsTask("Test");TaskService.Instance.Execute("notepad.exe").AtTaskRegistration().AsTask("Test");// ** New syntax with Version 2.8.13 **TaskService.Instance.Execute("notepad").OnIdle().When.ExecutingAtMost(TimeSpan.FromHours(8)).OnlyIfIdle().AsTask("Test");TaskService.Instance.Execute("notepad").OnIdle().AsTask("Test",TaskCreation.Create,"dahall@github.com",null,TaskLogonType.S4U);If you use the TaskEventLog constructor which specifies a remote machine, you will need to use impersonation to logon to an account with privileges to the remote machine before instantiating the TaskEventLog.
TaskEventLoglog=newTaskEventLog(task.Path);List<ListViewItem>c=newList<ListViewItem>(100);foreach(TaskEventiteminlog)c.Add(newListViewItem(newstring[](){item.Level,item.TimeCreated.ToString(),item.EventId.ToString(),item.TaskCategory,item.OpCode,item.ActivityId.ToString()}));