Today's note: scheduled tasks in ASP. NET Processes

Source: Internet
Author: User

Many times, weProgramYou need to regularly execute some tasks in the background thread, such as regularly sending emails. To put it simply, we can create a timer object and customize its callback events to meet specific business needs. For complex business requirements and high stability requirements, we can use some open-source frameworks such as quartz. Net to create a Windows service to execute scheduled tasks.

Although a separate Windows Service has good stability, quartz. Net can also meet various complex business needs. The background scheduled threads attached to ASP. NET processes are vulnerable to the impact of ASP. NET processes (timed recovery), resulting in unstable and unpredictable execution results. However, the background scheduled thread in the ASP. NET process after the append has the advantages of convenient deployment and independent installation. Under the premise of reasonable control and acceptable business requirements, the background timer thread in the lightweight ASP. NET process can still be widely used.

ASP. for example, you can directly use the timer object or use quartz. net; you can also directly use the thread pool to register the thread with delay. registerwaitforsingleobject is used to implement scheduled execution threads. Some people even use ASP directly. net cache to implement the background thread easy background tasks in ASP.. net. Because quartz. Net itself does not support running on medium trust level, and its complexity decides to abandon it in ASP. NET processes. To use a timer object, you must first compare and understand the timer objects in different namespaces. to select an appropriate object, refer to my previous blog. the timer object in the. NET Framework. It also controls the running status and cycle of the task, because these timer objects are basicallyReentrant, that is, when you want to execute a task that requires a long execution time, when your task time exceeds the interval, as long as the interval reaches, the same task will be executed in another thread, which may cause a conflict.The method of directly controlling the thread pool API is used to test scheduled tasks. Although there are no major problems in my practice, I have always worried that when the task is a little more, it will occupy a large number of threads in the thread pool.

For this lightweight small framework, developers of development tasks need to grasp the timing of tasks, that is to say, developers who develop scheduled tasks may not care about how the tasks are executed or where they are executed or how long they are separated. The task interface should be as follows:

 
Using system; using system. collections. generic; using system. LINQ; using system. text; namespace job {public interface ijob {void execute (Object executionstate); void error (exception e );}}

task execution is completed by a Unified Task executor:

Using system; using system. collections. generic; using system. LINQ; using system. text; using system. threading; namespace job {public class jobexecutor {public jobexecutor (ijob job, int interval, object executionstate) {This. job = job; this. interval = interval; this. executionstate = executionstate;} public ijob job {Get; private set;} public int interval {Get; private set;} public object executions Tate {Get; private set;} public bool started {Get; set;} public bool isrunning {Get; private set;} private timer; Public void start () {If (started) {return;} timer = new timer (New timercallback (timercallback), executionstate, interval, interval); started = true;} private void timercallback (object state) {If (! Started | isrunning) {return;} timer. change (timeout. infinite, timeout. infinite); try {job. execute (State);} catch (exception e) {job. error (E);} isrunning = false; If (started) {timer. change (interval, interval) ;}} public void stop () {timer. dispose (); timer = NULL ;}} task executor, used to configure the execution cycle and method of the task, and then execute the instances holding the tasks in a unified task container, keep them alive in the main thread:
Using system; using system. collections. generic; using system. LINQ; using system. text; using system. threading; namespace job {public class jobs {Private Static readonly jobs instance = new jobs (); Private dictionary <string, jobexecutor> jobs = new dictionary <string, jobexecutor> (); /// <summary> // gets the instance. /// </Summary> /// <value> the instance. </value> Public static jobs instance {get {return instance;} public void attachjob (string name, ijob job, int interval, object executionstate, bool start) {lock (lockhelper) {var jobexecutor = new jobexecutor (job, interval, executionstate); jobs [name] = jobexecutor; jobexecutor. start () ;}} static object lockhelper = new object (); Public void start () {lock (lockhelper) {foreach (VAR job in jobs. values) {job. start () ;}}/// <summary> // stops this instance. /// </Summary> Public void stop () {lock (jobs) {foreach (jobexecutor job in jobs. values) {job. stop ();}}}}}

The task container remains in the host process as a Singleton, either in the ASP. NET process or in the Windows service process. Compared with quartz. net, it is already a simple scheduled task framework. However, many times, if you host an ASP. NET process, it is not a wise choice to execute a scheduled task that runs on a daily, daily, weekly, or monthly basis.

The above framework was first learned from the source code of the Community Server. After years of modification and misunderstanding. Today, we finally return to the simplest implementation. If you have been entangled in a framework that requires simplicity, rich functionality, and minimal resources, then the road is not that easy.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.