Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a task in task schedular using "Run whether the user is logged on or not"

And also tell me about "Run whether user is logged on or not" in detail. to avoid future hurdles to run the created task(details about username and password)

like image 556
Dhamodran Avatar asked Dec 15 '22 20:12

Dhamodran


2 Answers

To create a task in taskscheduler with the setting: "run wether user is loggd on or not" use following code:

                    var taskDefinition = taskService.NewTask();
                    taskDefinition.RegistrationInfo.Author = WindowsIdentity.GetCurrent().Name;

                    taskDefinition.RegistrationInfo.Description = "Runs Application";

                    // TaskLogonType.S4U = run wether user is logged on or not 
                    taskDefinition.Principal.LogonType = TaskLogonType.S4U; 

                    var action = new ExecAction(path, arguments);
                    taskDefinition.Actions.Add(action);
                    taskService.RootFolder.RegisterTaskDefinition("NameOfApplication", taskDefinition);

Note: I dont work with a Trigger here. You can start the created task directly from code with following code:

                    //get task:
                    var task = taskService.RootFolder.GetTasks().Where(a => a.Name == "NameOfApplication").FirstOrDefault();

                    try
                    {
                        task.Run();
                    }
                    catch (Exception ex)
                    {
                        log.Error("Error starting task in TaskSheduler with message: " + ex.Message);
                    }
like image 127
Ephedra Avatar answered Jan 13 '23 14:01

Ephedra


You can set the UserId to SYSTEM and it will automatically set the option 'Run whether user is logged on or not'.

using (TaskService ts = new TaskService())
{
    var newTask = ts.NewTask();
    newTask.Principal.UserId = "SYSTEM";
    newTask.Triggers.Add(new TimeTrigger(DateTime.Now));
    newTask.Actions.Add(new ExecAction("notepad"));
    ts.RootFolder.RegisterTaskDefinition("NewTask", newTask);
}

The program executing the above code must run as Administrator.

Found this solution posted in the comments here, http://taskscheduler.codeplex.com/wikipage?title=Examples

like image 30
Despertar Avatar answered Jan 13 '23 13:01

Despertar