问题
I've a set of queries which I want to execute only once in day, I know this is possible using TaskScheduler in C#. But I am not getting any example suitable for my requirements. Can anybody give a example code for this?
回答1:
You can try FluentScheduler
. The documentation has the sample codes all you need. Firstly I thought it is for web only, but now I think you can use it for using with Desktop Application too. But not sure and not tested.
https://fluentscheduler.codeplex.com/documentation
EDIT You can also use Task Scheduler -
First create a console application that can run and do all your tasks. You can even invoke other processes with it. Then build the executable and save it in a safe location.
Then go to Administrative Tools > Task Sheduler And create a new task by clicking Action > New Task. You will see a screen like this -
Select your executable and other permissions there.
- Now to run it in schedule move to next tab 'Triggers' and click add at the bottom. You will see a screen like this -
Now add your desired schedules. Make sure you use logs, because you will not be able to see the outputs directly. Either you can use windows event viewer or write to custom text file for your convenience.
Task Scheduler is a part of windows itself. It does not have a dependency on C# or C++ anything. Basically you tell windows that it will run the specific program at a regular schedule. It is the job of the executed program to initialize all environment and execute appropriate code. So even if you use task scheduler you have to make sure that the program you are using to run with it, has all other options and codes right.
回答2:
The Timer is probably the best solution for you.
var timer = new Timer {AutoReset = true, Interval = 30000}; 1s = 1000ms
timer.Elapsed += timer_Elapsed;
timer.Start();
.......
public void timer_Elapsed(object source, System.Timers.ElapsedEventArgs e)
{
// do stuff here that will execute every 30 seconds
}
回答3:
If you need a reliable scheduler, writing your own from scratch might take more effort than expected. What if the machine gets rebooted? What if it happens 10 seconds before execution time? Should the task be executed late or not at all? Where will the data be persisted? You have to think about all these things.
Alternatively, you could use Quartz.NET. It is a C# port of popular Java job scheduling framework. The codebase is well tested and robust. Have a look at it here: http://www.quartz-scheduler.net/
来源:https://stackoverflow.com/questions/24135052/periodic-execution-of-particular-code-in-c-sharp