Search code examples
c#scheduled-taskswindows-task-schedulertaskservice

Can I run scheduled task using the TaskService object?


I've created a simple task. It is launched at the log on of every user. I'd also like to launch it right away after creation -> do what "Run" in Task Scheduler GUI does. I know that I can start a new process, and execute action target that way. Can it also be done just using the TaskService object? This is sample code:

using (TaskService ts = new TaskService()) {
    // Create a new task definition and assign properties
    TaskDefinition td = ts.NewTask();
    td.RegistrationInfo.Author = "Me";

    td.Principal.RunLevel = TaskRunLevel.Highest;

    td.RegistrationInfo.Description = "Starts Updater";
    td.Settings.DisallowStartIfOnBatteries = false;
    td.Settings.Enabled = true;
    td.Settings.ExecutionTimeLimit = TimeSpan.Zero;
    td.Settings.Hidden = false;
    td.Settings.IdleSettings.RestartOnIdle = false;
    td.Settings.IdleSettings.StopOnIdleEnd = false;
    td.Settings.Priority = System.Diagnostics.ProcessPriorityClass.High;
    td.Settings.RunOnlyIfIdle = false;
    td.Settings.RunOnlyIfNetworkAvailable = false;
    td.Settings.StopIfGoingOnBatteries = false;


    // Create a trigger that will fire the task at this time every other day
    td.Triggers.Add(new LogonTrigger());

    var fileName = Path.Combine(Environment.GetFolderPath("path_updater.exe");
    // Create an action that will launch Notepad whenever the trigger fires
    td.Actions.Add(new ExecAction(fileName, null, null));

    // Register the task in the root folder
    ts.RootFolder.RegisterTaskDefinition(@"Updater", td);

}

Solution

  • Just as you would right click a created Task and click Run on TaskScheduler GUI

    You can use Task.Run() after the task has been registered like this

    .
    .
    ts.RootFolder.RegisterTaskDefinition(@"Updater", td);
    var runCreatedTask = ts.FindTask("Updater").Run(); //Runs the registered task immediately