How can I do simple job scheduling with C#/.NET?
Assume I have a method (of a certain class) which I want to run automatically daily, hourly, weekly and so on.
Is there a simple method for doing this?
There are three ways you can do this in .net
1) create a windows service. If, on windows (assuming you are on windows 7), you tap the start button and type "view local services", then click on the result, everything you see here is a windows service. When you code a windows service, it is basically a console application wrapped in code that installs the service and sets the scheduling time. There are many tutorials on how create a windows service. Here is Microsofts guide: http://msdn.microsoft.com/en-us/library/zt39148a(v=vs.80).aspx
2) Create an "exe" application, and then put in "Task Scheduler". Again, hit the start button and search for "Task Scheduler". This differs from a windows service in that you you control the scheduling from the task scheduler, not in your application. Also, it used to be that you had to re-start scheduled tasks on a reboot, where as windows services can be set to start when the operating system starts (I am not sure if this rule still applies, I have not used task scheduler for a while). Here is Microsofts guide on how to do this: http://windows.microsoft.com/en-GB/windows7/schedule-a-task
3) You can also check out Quartz.NET which is an enterprise level job scheduling framework. I have used it several times and it works very well. Quartz.NET can be found here: http://quartznet.sourceforge.net/
One more thing you may want to take a look at is "Topshelf". This makes developing a windows service easier: http://topshelf-project.com. I have not used it myself, but know many people that have and they recommend it.
Edit after more detail added to question
If you are looking for a way you can call into a method on a class using some sort of cron job equivalent, there is no way to do this. You need to make this class part of an application (exe), and then use one of the methods above to schedule the execution of that exe.
The quickest and simplest way (not necessarily the best depending on your application needs) is to create a simple console application (http://msdn.microsoft.com/en-us/library/ms438026(v=office.14).aspx). Copy the class you are talking about into it, and then invoke the method that you would like to schedule in the main method of the application. Then use the task scheduler as described above.
Hope that helped.
If you have an ASP.NET application, the easiest thing is to have the Windows Task Scheduler invoke a special URL in your app using curl.exe
.
The Windows Task Scheduler can also be used to start a custom EXE of yours.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With