Schedule task in Windows Task Scheduler C# [duplic

2019-01-26 20:33发布

问题:

This question already has an answer here:

  • C# API for Task Scheduler 2.0 [closed] 4 answers

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)

回答1:

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?)



回答2:

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