This project has moved. For the latest updates, please go here.

How to set the "Run whether user is logged on or not"

Sep 22, 2012 at 11:53 PM

How can I set the "Run whether user is logged on or not" option?

I would like use this to ensure that a scheduled task run 5min aftet at startup.

 

    String strPath;

            BootTrigger cBootTrigger;
            cBootTrigger = new BootTrigger();
            cBootTrigger.Delay = new TimeSpan(0, 5, 0);

            strPath = "c:\\MyAPP.exe";
            using (TaskService ts = new TaskService())
            {
                TaskFolder tf = ts.RootFolder;

                // Create a new task definition and assign properties
                TaskDefinition td = ts.NewTask();
                td.RegistrationInfo.Description = "MyAppAtBoot";
               
                td.Principal.LogonType = TaskLogonType.InteractiveToken;

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

                    // Create an action that will launch Notepad whenever the trigger fires
                    td.Actions.Add(new ExecAction(strPath, null, null));

                    // Register the task in the root folder
                    try
                    {

                        ts.RootFolder.RegisterTaskDefinition(@"MyAppAtBoot", td);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());

      }
               
            }

 

Coordinator
Sep 24, 2012 at 11:51 PM

Typically, you would use the "SYSTEM" account to register a task with a BootTrigger. You would then use TaskLogonType.ServiceAccount. You will just need to make sure the Action being triggered does not require permissions the SYSTEM account does not have (like accessing network resources).

Sep 25, 2012 at 11:04 AM

Hi Dahall

Thanks for the reply, but I’m still stuck. Please have a look at the attached. Your guidance would be greatly appreciated.

This is a snipped from my code:

private void Schedule_ExecuteAtStartup(bool bAddorRemoveTask /*True add, False Remove*/)

{

String strPath;

BootTrigger cBootTrigger;

cBootTrigger = new BootTrigger();

cBootTrigger.Delay = new TimeSpan(0, 5, 0);

string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

strPath = System.Windows.Forms.Application.StartupPath + "\\ServiceWatcher.exe";

using (TaskService ts = new TaskService())

{

TaskFolder tf = ts.RootFolder;

// Create a new task definition and assign properties

TaskDefinition td = ts.NewTask();

td.RegistrationInfo.Description = "ServiceWatcherAtBoot";

td.Principal.LogonType = TaskLogonType.ServiceAccount;

if (bAddorRemoveTask)

{

Task CheckTask = ts.GetTask("ServiceWatcherAtBoot");

if (CheckTask != null)

{

Error_Log.WriteLog(true, false, "ServiceWatcher Schdule already exist...");

return;

}

// Create a trigger that will fire the task at this time every other day

td.Triggers.Add(cBootTrigger);

// Create an action that will launch Notepad whenever the trigger fires

td.Actions.Add(new ExecAction(strPath, null, null));//("D:\\My Documents\\Software Development\\ServiceWatcher\\ServiceWatcher\\bin\\Release\\ServiceWatcher.exe", null, null));

// Register the task in the root folder

try

{

ts.RootFolder.RegisterTaskDefinition(@"ServiceWatcherAtBoot", td);

}

catch (Exception ex)

{

Error_Log.WriteLog(ex.ToString());

}

}

else

{

// Remove the task we just created

ts.RootFolder.DeleteTask("ServiceWatcherAtBoot");

}

}

}

I get the following error when trying to add the task:

- ex {"(39,4):Task:"} System.Exception {System.Runtime.InteropServices.COMException}

+ [System.Runtime.InteropServices.COMException] {"(39,4):Task:"} System.Runtime.InteropServices.COMException

+ Data {System.Collections.ListDictionaryInternal} System.Collections.IDictionary {System.Collections.ListDictionaryInternal}

HelpLink null string

+ InnerException null System.Exception

Message "(39,4):Task:" string

Source "" string

StackTrace " at Microsoft.Win32.TaskScheduler.V2Interop.ITaskFolder.RegisterTaskDefinition(String Path, ITaskDefinition pDefinition, Int32 flags, Object UserId, Object password, TaskLogonType LogonType, Object sddl)\r\n at Microsoft.Win32.TaskScheduler.TaskFolder.RegisterTaskDefinition(String Path, TaskDefinition definition, TaskCreation createType, String UserId, String password, TaskLogonType LogonType, String sddl)\r\n at Microsoft.Win32.TaskScheduler.TaskFolder.RegisterTaskDefinition(String Path, TaskDefinition definition)\r\n at ServiceWatcher.ServiceWatcher.Schedule_ExecuteAtStartup(Boolean bAddorRemoveTask) in D:\\My Documents\\Software Development\\ServiceWatcher\\ServiceWatcher\\Form1.cs:line 734" string

+ TargetSite {Microsoft.Win32.TaskScheduler.V2Interop.IRegisteredTask RegisterTaskDefinition(System.String, Microsoft.Win32.TaskScheduler.V2Interop.ITaskDefinition, Int32, System.Object, System.Object, Microsoft.Win32.TaskScheduler.TaskLogonType, System.Object)} System.Reflection.MethodBase {System.Reflection.RuntimeMethodInfo}

+ Static members

+ Non-Public members

Kind Regards

From: dahall [email removed]
Sent: 25 September 2012 12:52 AM
To: Elco Grobler
Subject: Re: How to set the "Run whether user is logged on or not" [taskscheduler:396537]

From: dahall

Typically, you would use the "SYSTEM" account to register a task with a BootTrigger. You would then use TaskLogonType.ServiceAccount. You will just need to make sure the Action being triggered does not require permissions the SYSTEM account does not have (like accessing network resources).

Coordinator
Sep 25, 2012 at 5:03 PM

You need to specify the TaskLogonType in the RegisterTaskDefinition method call. Below is your code, with some optimizations, that works on my system.

const string taskName = "ServiceWatcherAtBoot";
using (TaskService ts = new TaskService())
{
   if (bAddorRemoveTask)
   {
      if (ts.GetTask(taskName) != null)
      {
         Error_Log.WriteLog(true, false, "ServiceWatcher Schdule already exist...");
         return;
      }

      // Create a new task definition and assign properties
      TaskDefinition td = ts.NewTask();
      td.RegistrationInfo.Description = "ServiceWatcherAtBoot";
      td.Triggers.Add(new BootTrigger() { Delay = TimeSpan.FromMinutes(5) });
      String strPath = System.Windows.Forms.Application.StartupPath + "\\ServiceWatcher.exe";
      td.Actions.Add(new ExecAction(strPath, null, null));

      // Register the task in the root folder
      try
      {
         ts.RootFolder.RegisterTaskDefinition(taskName, td, TaskCreation.Create, "SYSTEM", null, TaskLogonType.ServiceAccount);
      }
      catch (Exception ex)
      {
         Error_Log.WriteLog(ex.ToString());
      }
   }
   else
   {
      // Remove the task
      ts.RootFolder.DeleteTask(taskName);
   }
}