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!
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
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.
Try to change the version of the console application to 32 bit.
i.e. Right click Goto -> Properties -> Build -> Platform Target
= x86.
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.
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
Related
Launching of the desktop application was working fine when I automated using winAppDriver.
Of late I observed these tests are failing.
Its failing at this line,
notepadsession = new WindowsDriver(new Uri("http://127.0.0.1:4723"), desiredcapabilities);
I tried both the codes, but still failing:
var currentWindowHandle = notepadsession.CurrentWindowHandle;
Thread.Sleep(TimeSpan.FromSeconds(5));
var allWindowHandles = notepadsession.WindowHandles;
notepadsession.SwitchTo().Window(allWindowHandles[0]);
if (notepadsession.CurrentWindowHandle != notepadsession.WindowHandles.Last())
{
notepadsession.SwitchTo().Window(notepadsession.WindowHandles.Last());
}
NOTE: It takes around 40-50 seconds to load the Desktop application.
Any help in this regard is highly appreciated.
Thanks
Below code solved the problem
notepadsession = new WindowsDriver(new Uri("http://127.0.0.1:4723"), desiredcapabilities);
Thread.Sleep(5000);
notepadsession.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
The ms:waitForAppLaunch capability enables WinAppDriver to wait for a defined amount of time after an app launch is initiated prior to attaching to the application session. The limit for this is 50 seconds.
C#: appCapabilities.SetCapability("ms:waitForAppLaunch", "25"); to add app delay of 25 seconds.
For more information check out the release notes.
I am making a launcher app in C# on windows. However the process isn't directly started by my C# application but it uses a url to start it e.g "steam://rungameid/xxxxxxx"
I need it to monitor a process by name (say XYZ.exe) in the following fashion:
Receive an event when XYZ.exe starts
Receive an event when XYZ.exe exits
I just want to minimise and restore the my C# application's form when the application is running and not running respectively
thanks
Make a timer (with your preferred timer method) and poll every 'n' milliseconds (find what's best for you... I'd say for minimizing/restoring from a game, 500 milliseconds could be a good start, but experiment), then you can use something like:
bool processRunning = false;
void timerTickMethod()
{
var procIsRunning = Process.GetProcessesByName("xyz.exe").Any();
if(procIsRunning && !processRunning)
ProcessIsStartedEvent(); // or directly minimize your app
else if(!procIsRuning && processRunning)
ProcessIsEndedEvent(); // or directly restore your app
processRunning = procIsRunning;
}
If you want to make sure it's your xyz.exe that is running, you can pass in the full path to GetProcessesByName (so that if there's other xyz.exe in your system, it won't confuse your app)
Update
I was writing from memory, so maybe GetProcessesByName only work for friendly names (with no exe, or path).
If that's the case (I haven't tried), and you need the full path you could do it like:
var procIsRunning = Process.GetProcesses().Any(x => x.MainModule.Filename == #"c:\your\full\path.exe");
I have this kind of Task
private async Task SaveToFile(StorageFile file)
{
// prepare data
await ...
Debug.Writeline("completed");
}
If the user press "back" button this task won't be completed. I need a way to make it go on until all it's done, even if the calling app is not running any more.
You have To use "background Task" for this. Its pretty simple,
create a new project for background tasks and add it to your solution, because your background task is a not a simple class its a separate WINRT project. To do this, right-click on your solution node in the Solution Explorer and select Add->New Project. Then select the Windows Run-time Component (Universal Windows) project type, name the project, and click OK. I named here "BackgroundStuff". You can create more than one background task for single application. there is no any limit.
Consider simple example to generate toast even App is not running:
private async void button_Click(object sender, RoutedEventArgs e)
{
string myTaskName = "MyBackgroundClass";
// check if task is already registered
foreach (var cur in BackgroundTaskRegistration.AllTasks)
if (cur.Value.Name == myTaskName)
{
await (new MessageDialog("Task already registered")).ShowAsync();
return;
}
// Windows Phone app must call this to use trigger types (see MSDN)
await BackgroundExecutionManager.RequestAccessAsync();
// register a new task
BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder { Name = "MyBackgroundClass", TaskEntryPoint ="MybackgroundStuff.MyBackgroundClass" };
taskBuilder.SetTrigger(new TimeTrigger(15, true));
BackgroundTaskRegistration myFirstTask = taskBuilder.Register();
If you want to learn more , refer my blog:
http://windowsapplife.blogspot.in/
No, you can not force a Task to keep running, if the parent process is terminated.
That said, the issue you've described is not really an issue unless your file takes longer than 10 seconds to save (which is an eternity, in computer lingo).
Windows Phone apps continue to run in the background for up to 10 seconds, after the user 'backs' out of it, or manually quits. This should be enough time for any application to finish its 'cleanup' operations.
See: App Lifecycle Windows Runtime Apps
See also: App activation and deactivation for Windows Phone 8
I have a .net app that does a variety of file operations. It has been scheduled via task manager and runs without issue. We are moving the job to be controlled by autosys and have the job configured. When it kicks off I see all the files move as expected and I get a log file indicating that everything ran as expected. The app is working. Autosysy, however, reports that it failed.
Status/[Event] Time Ntry ES ProcessTime Machine
-------------- --------------------- -- -- --------------------- ----------------------------------------
RUNNING 09/26/2013 15:30:21 1 PD 09/26/2013 15:31:12
FAILURE 09/26/2013 15:31:59 1 PD 09/26/2013 15:32:17
[*** ALARM ***]
JOBFAILURE 09/26/2013 15:32:16 1 PD 09/26/2013 15:32:17
[STARTJOB] 09/26/2013 16:00:00 0 UP
The application is a winform app - here's the meat of the code:
static int Main(string[] args)
{
Console.WriteLine("Starting processing...");
Console.WriteLine(DateTime.Now.ToString(CultureInfo.InvariantCulture));
if (args.Length > 0) //if we call the app with args we do some stuff, otherwise we show the UI to let the user choose what to do
{
//stuff happens here that works, other method calls, etc.
Console.WriteLine(DateTime.Now.ToString(CultureInfo.InvariantCulture));
Console.WriteLine("Process complete.");
return 0;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FileLoader());
return 0;
}
The job IS working, it's doing everything that it is supposed to do without logging any exceptions BUT autosys still reports failure. What am I doing wrong?
Autosys will mark the job as successfully completed when the process ends. In your case you've told that it is an Win-Form application. So what may happen here is the autosys is starting the Application and also the application is working fine and it is doing what it suppose to do. But the process will not end unless untill someone manually close the window application or if you have some techinque to close itself. And so Autosys is assuming that the process not ended thus marking the job as failed.
The solution for this is make your application as console application or else I remember there is one property when setting up the Autosys job not to consider the Process ending so the job will just start the program and mark the job as completed.
I have a Windows scheduled task that runs a database import process every hour, but I'd like users to be able to kick it off out-of-schedule by hitting a button in an ASP.net dashboard (running in IIS6 on Windows Server 2003).
The following works perfectly in code-behind ...
var proc = new Process
{
StartInfo =
{
UseShellExecute = false,
FileName = #"C:\Windows\System32\schtasks.exe",
Arguments = "/run /tn Loader",
RedirectStandardError = true,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
proc.WaitForExit();
... but only if the application pool identity is set to Local System (not ideal!). If I leave it as Network Service, the task does not start. So it is presumably a permissions issue.
Is there a way ASP.net can kick off a scheduled task on the server without running the application as Local System? If not, what good alternatives are there?
Update: if nobody on SO knows, I guess it is not possible so I will go with my idea of having my web application write requests to a database table (doubling as an audit log) and creating a second task to poll that table and kick off the main task.
Update your schedule task to trigger off a specific event. Then have your website log that event when the button is clicked - thus starting your scheduled task.
Ex:
In my installer I create an event log source for my program, since creating the source requires administrative privileges (you can also use the command line to create the source)
if (EventLog.SourceExists("MyApp"))
{
EventLog.CreateEventSource("MyApp", "Application");
}
Then in my application, I create an event log entry when the button is clicked.
private void btnOpenOtherApp_Click (object sender, EventArgs e)
{
try
{
var log = new EventLog
{
Source = "MyApp"
};
log.WriteEntry("Start MyOtherApp", EventLogEntryType.Information, 1337);
}
catch (Exception ex)
{
...
}
}
And the task scheduler set to open MyOtherApp when the event is logged.
You need an administrator user in windows. This code will help you to call the task:
var securePass = new System.Security.SecureString();
foreach (char c in "my_password")
{
pass.AppendChar(c);
}
var proc = new Process
{
StartInfo =
{
UseShellExecute = false,
FileName = #"C:\Windows\System32\schtasks.exe",
Arguments = "/run /tn Loader",
UserName = "myAdminUser", //NEW
Password = securePass, //NEW
RedirectStandardError = true,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
proc.WaitForExit();
If your application needs to run as SYSTEM Account you can use this arguments:
If the /RU username and /RP Password parameters match the currently
logged-in user, the task will run interactively (visible in the
foreground).
For the system account, /RU username can be written as "", "NT
AUTHORITY\SYSTEM" or "SYSTEM", a Password is not required. The system
account has full access to the local machine but has no permissions on
any other machines (or mapped drives) across the Network.
Source: http://ss64.com/nt/schtasks.html
You can utilize the cache of ASP.NET to run schedule tasks. I personally used this and it worked like charm. Ofcourse it has some limitation (Accuracy) but you can adjust/change.
https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/
Regards
If using a 3rd party scheduler service such as Quartz.NET is not an option, and changing permissions is not allowed either (not a good idea in any case) another possibility is to to write a helper Windows service as a bridge between ASP.NET application and Windows scheduler. You would store list of tasks in a DB and a sequence of events would be something like this:
When you need to run a task, from ASP.NET GUI you set flag in the DB for that task
Helper service runs on schedule to check the DB at given intervals - sees the flag, starts the task, reset the flag.
Oh and there're libraries out there (e.g. http://taskscheduler.codeplex.com/ and others) that wrap Window Task Scheduler, so you don't have to execute them directly, but rather in a nice managed way.