Using Fluentscheduler to dispatch tasks in Gizhgara Dotnet.webform

Source: Internet
Author: User
Tags dotnet hosting

Some users have been said that the system sent mail has not been received, the complaint system is not normal, at this time how to wash grievances? Each email sent will be saved to the database, and logs sent to the user, so that users have nothing to say.

Create 3 Tables yourself:

    1. Messagefailed-Failed record (more than 5 send failures are saved here)
    2. MessageQueue-Information Queue (successfully put Messagesucceed, failed 5 times to save to messagefailed)
    3. Messagesucceed-Success Record

With Fluentscheduler, dispatch directly on the web side, eliminating the Windows service program.

Fluentscheduler

Automated job scheduler with fluent interface.

Related code, I used the iregisteredobject to avoid the application pool and the process restart caused by job interruption and other exceptions:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;namespacedotnet.business{usingDotnet.model; usingdotnet.business; usingdotnet.utilities; usingFluentscheduler; usingSystem.Web.Hosting; #regionMessageregistry Public Partial classMessageregistry:registry { PublicMessageregistry () {//No repeat entry allowedNonreentrantasdefault (); //Schedule an IJob -to-run at an intervalSchedule<messagejob> (). Nonreentrant (). Torunnow (). Andevery (1).            Seconds (); ////Schedule An IJob to run once, delayed by a specific time interval            //schedule<messagejob> (). Torunoncein (5). Seconds ();            ////Schedule A simple job -to-run at a specific time            //Schedule (() = Console.WriteLine ("It's 9:15 PM now."). Torunevery (1). Days (). at (+);            ////Schedule A more complex action to run immediately and on an monthly interval            //schedule<messagejob> (). Torunnow (). Andevery (1). Months (). Onthefirst (Dayofweek.monday). At (3, 0);            ////Schedule Multiple jobs to being run in a single Schedule            //schedule<messagejob> (). Andthen<messagejob> (). Torunnow (). Andevery (5). Minutes ();        }    }    #endregion    #regionMessagejob Public Partial classMessagejob:basemanager, Ibasemanager, IJob, IRegisteredObject {Private ReadOnly Object_lock =New Object(); Private BOOL_shuttingdown;  PublicMessagejob () {//Register This job with the hosting environment. //allows for a more graceful stop of the job, with the case of IIS shutting down.Hostingenvironment.registerobject ( This); }         Public voidExecute () {Lock(_lock) {if(_shuttingdown)return; //Do work , son!                NewMessagequeuemanager ( This. UserInfo).            Resend (); }        }         Public voidStop (BOOLimmediate) {            //Locking here'll wait for the lock in Execute to be released until this code can continue.            Lock(_lock) {_shuttingdown=true; } hostingenvironment.unregisterobject ( This); }    }    #endregion}

When scheduling, the schedule in Global.asax is as follows:

// Fluentscheduler Task Scheduling FluentScheduler.JobManager.Initialize (new DotNet.Business.MessageRegistry ());

Message-related code, messagefailed messages in the Send Error record is not implemented temporarily:

#regionResend Message/// <summary>        ///Resend Message/// </summary>        /// <param name= "id" >PRIMARY Key</param>        /// <returns>is successful</returns>         Public BOOLResend (messagequeueentity entity,intMaxfailcount =5)        {            BOOLresult =false; if(Entity. Messagetype.tolower (). Contains ("Mail"))            {                if(Mailutil.send (entity. Recipient, entity. Subject, entity. Body)) {//send success, move data to Messagesucceed tableMessagesucceedentity entitysuccesed =Newmessagesucceedentity (); Entitysuccesed.messagetype=entity.                    MessageType; Entitysuccesed.recipient=entity.                    Recipient; Entitysuccesed.subject=entity.                    Subject; Entitysuccesed.body=entity.                    Body; Entitysuccesed.createon=entity.                    Createon; NewMessagesucceedmanager ( This. UserInfo).                    ADD (entitysuccesed); //Delete data from the MessageQueue table//This . Delete (entity. ID);                     This. DeleteObject (entity.                    ID); Result=true; }                Else                {                    //update the number of failures in the MessageQueue tableEntity. Failcount = entity. Failcount +1;  This.                    Updateobject (entity); if(Entity. Failcount >=Maxfailcount) {                        //send failed more than 5 times, move data to messagefailed tableMessagefailedentity entityfailed =Newmessagefailedentity (); Entityfailed.messagetype=entity.                        MessageType; Entityfailed.recipient=entity.                        Recipient; Entityfailed.subject=entity.                        Subject; Entityfailed.body=entity.                        Body; Entityfailed.failcount=entity.                        Failcount; Entityfailed.createon=entity.                        Createon; //entityfailed.error = "";                        NewMessagefailedmanager ( This. UserInfo).                        ADD (entityfailed); //Delete data from the MessageQueue table//This . Delete (entity. ID);                         This. DeleteObject (entity.                        ID); Result=false; } result=false; }            }            returnresult; }        #endregion        #regionResend All queues/// <summary>        ///Resend all Queues/// </summary>        /// <returns>number of successful sends</returns>         Public intResend (intMaxfailcount =5)        {            intresult =0; //every time you send a letter, avoid timeouts, tasks are started and listentity is not re-acquired.List<messagequeueentity> listentity = This. Getlist<messagequeueentity> (1, Messagequeueentity.fieldid); foreach(varEntityinchlistentity) {                if( This. Resend (entity, Maxfailcount)) {result++; }            }            returnresult; }        #endregion

Because this background job scheduling is sent by mail, in fact, MVC Project can also directly use the above code.

Using Fluentscheduler to dispatch tasks in Gizhgara Dotnet.webform

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.