简体   繁体   中英

Windows task scheduler created programmatically in C# not running automatically

I have created windows task scheduler programmatically in c#. Task is created successfully and is scheduled to run correctly. At scheduled time, it says task is running but without any result and next schedule time is updated.

But last run time and last run result does not update.

Last run result is: The task has not yet run.(0x41303)

But when run manually from task scheduler it executes successfully but not automatically.

Below code that i used to create task

var ts = new TaskService();
var td = ts.NewTask();
td.RegistrationInfo.Author = "My company";
td.RegistrationInfo.Description = "Runs test application";
var trigger = new WeeklyTrigger { StartBoundary = startDate, DaysOfWeek = daysOfWeek, Enabled = enabled };
trigger.Repetition.Interval = TimeSpan.FromSeconds(((minutes == 0) ? 60 : minutes) * 60);
td.Triggers.Add(trigger);
var action = new ExecAction(Assembly.GetExecutingAssembly().Location, null, null);
if (filePath != string.Empty && File.Exists(filePath))
{
    action = new ExecAction(filePath);
}
action.Arguments = "AutoRun";
td.Actions.Add(action);
ts.RootFolder.RegisterTaskDefinition(TaskName, td);

Any help would be much appreciated!

Turns out, for running any task in scheduler, laptop charger must be plugged in else scheduler does not execute the task.

This is not the case with windows server or desktop systems.

Not sure about this behavior but this is what i figured it out.

Check the execution privileges first. Then check the task manager if the process is really running when it seems 'running'. If yes, try to use some try-catch blocks and create event logs as exceptions.

I think when you run manually from task scheduler, its executed by a user that belongs to task scheduler (maybe administrator). But at scheduled time, application trying to be executed as a user that won't have enough privileges to do some stuff in your code.

UPDATE

  1. Set Start in (optional) value to target file location. Without it, the task scheduler runs in system32 folder but like i said before, target application wouldn't have privileges to run in system32.
  2. Try to change the version of the console application to 32 bit.

    ie Right click Goto -> Properties -> Build -> Platform Target = x86.

For me the issue was the executable crashing with "Application Error". You can't see any error in Task scheduler. It will just show last run result as "The task has not yet run.(0x41303)"

TO get the error please check Event Viewer

EventViewer -> Windows Logs -> Aplication

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM