Implementing a job scheduler for ASP.NET MVC
I need to execute some activities/jobs in my Web Server, such as indexing some information, organizing some files, and calculating some statistics...
I want to preserve the QoS in my Web Server (performance, memory consumption, ...). So I'm thinking of executing an external process for these activities, instead of calling in a thread. Something similar to Apache MPM processer (it launches child processes to process the requests).
- Do know any bes开发者_如何学编程t solution to do this?
- Do you know any library that could do this for me?
Thanks in advanced.
You may take a look at Quartz.NET which allows you to schedule jobs which will run on the server.
Could you do something like they use on the Stack Exchange sites?
https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/
Well, I finally implemented a system to execute tasks/jobs in a external process.
If someone want to know how I implemented it, here are some of the details. Maybe I will write an article to share the solution and the source code.
Basically, we have two components, the Web.dll
(ASP.NET application) and a program called TaskExecutor.exe
In the Web.dll
, there is an activity scheduler that can register tasks by name: for example:
ActivityScheduler.Get().RegisterActivity("GenerateSearchIndexes", 4 * 1000 * 60 * 60); //each 2 hours
The activity scheduler executes each activity in a thread, and this thread calls an external process, the ActivityExecutor.exe
This assembly has a reference to the Web.dll
that has a static ActivityFactory to get the activities. The source code of the external process is quite simple:
public static void Main (string[] args)
{
try
{
if (args.Length == 0)
{
throw new ArgumentException("No activity name given", "ActivityName");
}
//parameter 0 is the activity name
string activityName = args[0];
IScheduledActivity activity = ActivityFactory.GetActivity(activityName);
if (activityName != null)
{
activity.Execute(args);
}
}
catch (Exception ex)
{
Console.WriteLine("Error executing activity: " + ex.Message);
}
}
As you can guess the restriction here is that the activities must be statically defined, so they cannot receive paramenters in its constructor. The are passed in the IScheduledActivity.Schedule(string[] args)
method, in the same way as a program would do.
精彩评论