Home > Mobile >  C# Using TaskScheluder creates task but does not executes it
C# Using TaskScheluder creates task but does not executes it

Time:08-24

I've created simple script by using this: https://github.com/dahall/TaskScheduler package that is supposed to check the time and if it's after 14:30 create schdule to put the computer to hibernation 15 minutes after the task is created.

The task creating code looks like this:

    static void CreateTask(string taskName)
    {
        TaskDefinition td = TaskService.Instance.NewTask();
        td.RegistrationInfo.Description = "Powers off the computer at "   Time(15);

        TimeTrigger tTrigger = new TimeTrigger();
        tTrigger.StartBoundary = Time(15);
        td.Triggers.Add(tTrigger);
          
        td.Actions.Add(new ExecAction("shutdown -h"));

        TaskService.Instance.RootFolder.RegisterTaskDefinition(taskName, td);

        Console.WriteLine("Task created successfully");
    }

The task is created with this sript but it does not run the task for some reason that I don't know why, can you please help me with this?

EDIT: Forgot to add my Time method, it's imple:

    static DateTime Time(int minutesToAdd)
    {
        DateTime timeNow = DateTime.Now;
        DateTime timeCalculated = timeNow.AddMinutes(minutesToAdd);

        return timeCalculated;
    }

CodePudding user response:

I came up with somewhat a solution.

There seems to be something with the Action being just a command. So I changed the action to run CMD and input command /C shutdown -h and it works

td.Actions.Add(new ExecAction(@"C:\Windows\System32\cmd.exe", "/C shutdown -h", null));

CodePudding user response:

is it displayed on Task Scheduler as Enabled?

follow this

  1. Press Windows R, type msc in Run box, and press Enter to open Windows Services.

  2. Scroll down in Services window to find Task Scheduler. Right-click Task Scheduler and choose Properties.

  3. In Task Scheduler Properties window, you can set the Startup type as Automatic.

  4. Then click Start, Apply, and OK to turn on Task Scheduler service.

  • Related