Add scheduled task and run even if on battery power

Just wanted to share a little helpful snippet in case anyone needs it. To add a scheduled task and make sure it starts even when on battery power do this:

using (var taskService = new TaskService())
    TaskDefinition task = taskService.NewTask();

    var action = new ExecAction
        Path = "test.exe",
        Arguments = "",
        WorkingDirectory = ""

    task.RegistrationInfo.Description = "Test";

    var trigger = new TimeTrigger(DateTime.Now);
    trigger.Repetition.Interval = TimeSpan.FromMinutes(5);


    task.Settings.DisallowStartIfOnBatteries = false;
    task.Settings.StopIfGoingOnBatteries = false;

    // Register the task in the root folder
    taskService.RootFolder.RegisterTaskDefinition("test", task, TaskCreation.CreateOrUpdate, "SYSTEM", null, TaskLogonType.ServiceAccount, null);

TaskService is part of Microsoft.Win32.TaskScheduler.

By default when you create a new task DisallowStartIfOnBatteries and StartIfGoingOnBatteries are true, so that’s something to keep in mind if you are writing code that can be deployed on a laptop and you must have your scheduled task continue to run.

Quick side note, I personally think negative property names are hard to follow (DisallowStartIfOnBatteries). It’s hard to follow when it becomes a double negative. I think it would’ve been much better to name the property


Especially since it has nothing to do with starting the task when its not on batteries. It’s interesting that the UI control for this doesn’t use a double negative to display the context (even though the phrasing is logically inverse). Still, case in point


Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>