Pages

Tuesday, September 30, 2014

C and Windows Task Scheduler is difficult

Apparently its not easy from C# program to interact with Windows Task Scheduler. From researching online, Windows Task Scheduler exposes COM APIs. However, from experience, using COM Apis from C# is a bit of a hassle, to say the least. 

Easy solution:
Ironically, it looks much easier to use command-line tools
"at" and "schtasks".

http://technet.microsoft.com/en-us/library/cc738335(WS.10).aspx

One problem with "schtasks" is that when it creates task, it will mark it "Start the task only if the computer is on AC power". This setting is inconvenient because its impossible to use when laptop runs on battery. 



Probably "Start the task only if the computer is on AC power" is default Windows settings unfortunately. Luckily schtasks.exe accepts a task definition XML file where its possible to override that setting.

All you need to do is to specify "DisallowStartIfOnBatteries" tag in task definition XML file.
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>

Heres a complete task schedule definition of PicturethrillTask.xml file from Picturethrill project http://picturethrill.codeplex.com/. This task allows Picturethrill.exe program to be executed every day and update users background image.

<?xml version="1.0" encoding="utf-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <Triggers>
    <CalendarTrigger>
      <StartBoundary>2012-01-17T03:30:00</StartBoundary>
      <Enabled>true</Enabled>
      <ScheduleByDay>
        <DaysInterval>1</DaysInterval>
      </ScheduleByDay>
    </CalendarTrigger>
  </Triggers>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>true</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT1H</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>"C:Users
ikoAppDataLocalAristovPicturethrillPicturethrill.exe"</Command>

      <Arguments>-q -n</Arguments>
    </Exec>
  </Actions>
</Task>

To create task using PicturethrillTask.xml file:
schtasks /create /TN Picturethrill /XML PicturethrillTask.xml

Enjoy, use schtasks from C# in your awesome software solutions :)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.