Schedule task in Windows Task Scheduler C# [duplicate] - c#

This question already has answers here:
C# API for Task Scheduler 2.0 [closed]
(4 answers)
Closed 5 years ago.
My application requires a re-start at midnight time daily. For this job, according to me, the task scheduler would be the ideal thing to use but I haven't been able to find how to use the Task Scheduler APIs in C# (no external libraries to be used)
Once starting the application from Task Scheduler is done, I also wanted suggestions how to shutdown the application automatically at a certain time (even if the app at that particular time might be unresponsive, displaying some error message box or not working due to some problem)

Well, I suppose you don't know about the schtasks command.
You could simply open a command prompt and type schtasks /? to see the options available.
The one needed here is /create. Of course this option requires a series of parameter to configure your scheduled task. But at the end you could resolve all calling:
Process.Start("schtasks", commandParams);
For the close process part, I use a little utility called pskill found in the Sysinternals suite from Microsoft's Mark Russinovich. Also this could be called inside a batch file set as scheduled task.
EDIT: Changed from psshutdown to pskill (You need to close only your app right?)

I suggest you write a service to handle this. Also, why does it require a restart?
If however you must use task scheduler, try it like this:
schtasks /create /SC DAILY /TN AppName /TR AppExecutablePath /ST 0
0:00 /ET TIMEFORENDTASK
You can simply type this in a batch script and run the batch script when the user is installing the app, then put this in the uninstall batch script:
schtasks /delete /TN AppName

Related

Where is Task Scheduler console output? (C# console app)

I am running a C# windows console application and passing in a couple of arguments via Task Scheduler. It runs all day loading flat file data created by other applications into SQL server. The program fails intermittently and I have Try/Catch logic that writes information regarding the exception using Console.WriteLine().
So basically I need to track down the location of the console output so I can take steps to eliminate the intermittent failures. I've had a good look around online thinking this must be a fairly common requirement to diagnose errors from Task Scheduler scheduled apps. My online search has revealed a couple of work around solutions but no direct answer as to where the console output goes when running a c# console application directly via Task Scheduler.
The two workarounds I have seen are:
(1) Get Task Scheduler to run a windows batch script (.bat file) instead of running the console app (.exe file) directly. Within the batch script use ">" or ">>" to redirect the console output to a flat file (e.g C:\app\myapp.exe arg1 arg2 > "C:\log\myapp_console_output.txt")
(2) A very similar solution is to get Task Scheduler to run the windows command line cmd.exe with /C option and passing arguments into cmd.exe to run my console app and also redirect the console output. e.g. something like:
cmd.exe /C "C:\app\myapp.exe" arg1 arg2 > "C:\log\myapp_console_output.txt"
While I acknowledge that the above workarounds may well help me to capture future failures it doesnt really help me to track down output from the intermittent failures that have already occurred. They also seem quite messy workarounds to achieve what I would have thought was a pretty common standard requirement.
Can anyone please confirm that the console output is definitely not retained somewhere when running a c# console app directly via Task Scheduler?

Uninstall Custom Action Not Deleting Registry Key

In my program, I create a registry key under current user. This program is run by the Task Scheduler with the highest permissions (S-1-5-32-545).
In my uninstall custom action, I have code to delete this key.
The code to delete the key works when I run as administrator.
The code does not work when run from the uninstall custom action.
I'm guessing that the reason it doesn't work in the latter case is because current user is different when the uninstaller executes than when local admin executes the code.
How can I delete this registry key when run from the uninstall custom action? How do I point the uninstall custom action to the correct current user?
I am largely unfamiliar with the use of task scheduler in Windows 10. I used it a lot back in the day in Windows 2000, and then it was very primitive - severely lacking in features I needed.
I'll just try to add some observations for you, bear with me if it isn't quite an answer. Please update your question with more details if this is the case - so we can understand exactly what you need.
Adding / Deleting Scheduled Tasks
I am wondering how you are creating the scheduled task? Are you hacking the registry directly? You should probably use schtasks.exe to create and delete it by command line with your WiX package. Here is one question / answer where they are dealing with the same issue: WIX Create Scheduled Task.
You already know this, but this is for others too:
Create your scheduled task manually using the scheduled task console.
Hold down Windows Key, tap R
Type in: taskschd.msc and press Enter
Now create your task manually in the scheduled task GUI and test it.
Create / Delete the scheduled task with schtasks.exe via a Quiet Execution Custom Action in your WiX package.
You can export an XML with the task settings and use it with schtasks.exe. I haven't tested this, but there is a sample here: Use an XML task file with Schtasks.exe in your WiX package.
You can also push command lines with MSI properties as shown here: WIX Create Scheduled Task.
Storage of Scheduled Tasks
It seems the scheduled tasks are not stored in the user section of the registry (HKCU), but on disk and in the per-machine section of the registry (HKLM): Where does Windows store the settings for Scheduled Tasks console? This should mean that they are deletable for all users on the machine by simply deleting them on uninstall. How does your HKCU registry key enter the picture? Here is the MSDN page on Schtasks.exe.
Alternatives to Scheduled Tasks
Just for the record, there are some alternatives to running your application as a scheduled task which may be better or easier than a scheduled task:
You can run your application as a Windows service.
This is a developer heavy "solution" requiring code changes, but is probably the most reliable - especially for business critical stuff.
See this summary: When should I use a scheduled task instead of a Windows Service?
Windows Services are more reliable for 24/7 tasks.
Scheduled tasks for stuff that happens "every now and then" (even once at logon).
"In summary, a scheduled task is often better for periodic, maintenance-type chores that don't demand sophisticated control".
Services should normally be run as LocalService, LocalSystem, Network Service - without a GUI - but it can also be run with user credentials.
Windows Services Frequently Asked Questions (FAQ). Just for reference and "safekeeping" of the link.
See some information on different service accounts you can use here: The difference between the 'Local System' account and the 'Network Service' account?
Does your application present an actual GUI to the user? It seems this is no longer possible (since Vista): interactive services. I have asked whether this is accurate or not or if "history has changed again". Phil Wilson (MSI expert) can probably tell us - I read an article of his on services back in the day.
You can use the startup folder for allusers as suggested here.
There are several options here. Please check link. There are further links in the linked article that should be worth a quick read.
Register in the registry to launch on boot / login.
Nice Tool: autoruns64.exe. If you really want to figure out a plethora of ways to run something on boot (by registering it in the registry), you could use the Sysinternals tool autoruns64.exe (that is a direct download link from the live sysinternals tool share, here is the Microsoft page).
This tool really shows you just how many ways things can be scheduled to run when the system starts up by being registered "somewhere in the registry". Drivers, services, scheduled tasks, IE, WinLogon, and much more. Perhaps uncheck the "Hide" entries in the Options menu to be truly perplexed by the number of relevant keys (heaps of malware vectors).
Warning: this tool is not for normal users. It has all the rope you need to shoot yourself in the foot if you don't know what you are disabling. Developer / sys-admin only please. Strangely enough it doesn't look like the startup folders in the user-profile are listed in the tool - I guess it is a tool concerned with registry-based launchers only. A screenshot I found:

How to make my WPF application to running when Windows OS is run c# [duplicate]

This question already has answers here:
How do I set a program to launch at startup
(13 answers)
Closed 6 years ago.
I have app who is need to working when Windows OS is starting. Is it possible to make my WPF application to running when Windows OS is running like Skype. I using .NET Framework 4.5.2.
For my application info is need only make QR Code and print with label printer. Is not really important to have some user interface.
The most common ways are:
Make it a service. You are mentioning WPF but then you are mentioning you don't need a user interface. Services by default can't have user interfaces, if you need one, you'll need to make a helper application: the most common way of handling this is using the same executable with a command line argument (one to start as service, without UI, and one to start as the helper app which communicates with the service).
Make it a task on the task scheduler, to make it run on boot use a trigger (there's a On startup trigger). You can use the command line:
SCHTASKS /Create /TN YourTaskName /TR C:\Path\To\Application.exe /MO ONSTART
(you can use ONLOGON instead of ONSTART if that's better for you)
Add your application to the Run list on the registry, in, for example, [HKCUor HKLM]\Software\Microsoft\Windows\CurrentVersion\Run
There are others (start menu, etc.), but these three are the most common
Jcl mentioned the service options. There's also the good ol' Startup folder option:
%programdata%\Microsoft\Windows\Start Menu\Programs\Startup <-- Common
%appdata%\Microsoft\Windows\Start Menu\Programs\Startup <-- Current User
Place a shortcut there, and your program will start when Windows starts and user logs in. If you place it into the Startup folder for all users (common), you'll probably need administrative permissions.
Do the following:
Click Start button
Click Control Panel
Click System and Maintenance
Click Administrative Tools
Select Task Scheduler
Or just type "Task Scheduler" in the start menu.
Here you can create a new task. As Trigger you would choose "On Start" or something similar.
As action you would pick the executable file for your WPF application.

Create Shortcut to Programmatically Created Scheduled Task

I'm working on a little time saving project for an installation of a software program and i'm having some real difficulties finding anything helpful.
What i'm trying to do is programmatically create and implement the common UAC workaround for executable's.
Where i'm at right is:
The executable automatically forces the user to run it as an administrator. Giving "complete" access (ie no "access denied" errors).
I programmatically create a "Scheduled Task" for an executable with no triggers that is set to run an executable with highest privelages.
The next step is to create a shortcut icon for this scheduled task (and ultimately populate it into the startup folder). This is where i'm having trouble.
I cannot, for the life of me, figure out how to create an icon that executes a scheduled task.
What i'm trying to do is here:
http://www.techsupportalert.com/content/how-create-program-shortcut-run-without-uac-prompt-windows-7.htm
It's the 7 steps following the first 12 steps.
The things i've thought of and could not figure out / find any information on are:
Programmatically running cmd command that will do this.
Locating executable for scheduled task and setting that as a shortcuts path (apparently there are no executable's for scheduled tasks).
I appreciate any help or thoughts on this.
I've tried and can't really find anything on this for help.
schtasks /run /tn TaskName
But you need to be an administrator.
There is no way around this. Security that can be avoided is not security.

How do I run my c# program as a scheduled task

I am still pretty much new to c# so you will have to bear with me.
I have developed a windows form program which updates some SQL records as an end of day process for one of our clients.
The next step is that I need to install the program on a server and simulate a button click in the program to become a scheduled task.
I know how to setup the task on the server side where you start program and enter the arguments. But I am unsure as to what code I need to include in my program to achieve this.
Consider using Windows Task Scheduler.
You could extract your business logic to a separate DLL and write a simple Console app that will just run your task after accepting the parameters through command line.
My recommendation would be to get away from running a GUI-based/windowed application from a scheduled task - this is generally madness in practice. Ideally, deploy a console-based version of your application that requires execution (perhaps with parameter arguments) and doesn't require any user (or quasi-user-) interaction.
If you simply can't create a 'system version' of your application, then I guess you have two choices, both immensely ugly: 1) create some kind of macro script which is executed instead of your program, this script could execute the program and issue 'the click', 2) perform 'the click' on startup of your application by invoking the button click handler (maybe based on a parameter to give it a duality in execution modes.)
I think you are also asking about command-line argument passing. See the answers to this question.
In particular, I highly recommend the accepted answer: NDesk.Options.
I have similar task to do making winforms as windows task. what i did is
in windows task scheduler in the task tab,under Run put your exe and then /Auto,it will run as schedule.
Example:winform.exe /Auto
If I'm understanding your question correctly, this is how you could possibly proceed:
Best way to parse command line arguments in C#? -> check the answers and choose a library to process the args or write your own code to do so.
Create a scheduled task if those arguments are present by Creating Scheduled Tasks
If it is a windows application, just go to the bin folder, get the executable file, and finally schedule a task for it by using windows schedule task and choose the exe file as you targeted application.
if it is web application, you may want to include your code in a quartz.net scheduled job, details are on quartz.net website.
Very popular solution is Quartz.NET http://quartznet.sourceforge.net/
Take a look in the Timer class
http://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx
Why not extract your database update logic as a windows service
you can segregate the sql handling part in a separate DLL and use the common DLL for both your form application and the windows service.
A window service run in background and can be automatically started when the computer boots, can be paused and restarted, and do not show any user interface.
Moreover you need not to install any third party software for same and window service code base can be ported to any windows machine with required version of .Net Framework installed.
Add reference: Microsoft.Win32.TaskScheduler
then write this code:
using (TaskService ts = new TaskService())
Microsoft.Win32.TaskScheduler.Task task = ts.GetTask(TaskName);
task.Run(); //start
task.Stop(); //End

Categories

Resources