Search code examples
windowsscheduled-tasksinno-setuptaskschedulerpascalscript

Inno Setup change an existing Windows Scheduled Task to run when on battery power


By default Windows Scheduled Tasks are created with the 'Start the task only if the computer is on AC power' setting enabled.

Scheduled Task

It is not possible to change this setting using schtasks.exe, which would have been the simple solution. However, it appears that it is possible to do this through the Windows API ITaskSettings::get_DisallowStartIfOnBatteries method. Can this be imported into Inno Setup in order to disable this setting, on an existing Scheduled Task, and allow it to run when the computer is on battery power? If so, how would this be done? Or is there another way to change this setting using Inno Setup?


Solution

  • Actually, it's possible to set that option using schtasks. You just have to use XML definition of the task.

    For your particular option, you need to set DisallowStartIfOnBatteries to false:

    <?xml version="1.0" encoding="UTF-16"?>
    <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
      <!-- ... -->
      <Settings>
        <!-- ... -->
        <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
      </Settings>
    </Task>
    

    For more, see How to add a scheduled task on network connection/disconnection event with Inno Setup.


    I didn't find a way to use the API to modify an existing task. This does not have any effect:

    var
      TaskService: Variant;
      Folder: Variant;
      Task: Variant;
    begin
      TaskService := CreateOleObject('Schedule.Service');
      TaskService.Connect();
      Folder := TaskService.GetFolder('\');
      Task := Folder.GetTask('test');
      Task.Definition.Settings.DisallowStartIfOnBatteries := False;
    end;