ASP.NET MVC5 Implementation of Quartz.NET-based Task Scheduling

Keywords: ASP.NET Database github xml

After work. Technology? It is impossible to remember. Only by writing something can we live like this. It's like writing an article about task scheduling. It's too lazy after all.

Introduction to Quartz.NET

Quartz.NET is a powerful, open source, lightweight job scheduling framework. It is a. NET porting of OpenSymphony's Quartz API. It can be rewritten with C # and used in winform and asp.net applications. It is flexible and not complicated. You can use it to create simple or complex job scheduling for executing a job. It has many features, such as database support, clustering, plug-ins, support for cron-like expressions and so on.

Official website: http://www.quartz-scheduler.net/

Source: https://github.com/quartznet/quartznet

II. Use of Quartz.NET

First, regular email notifications can be made.  

Second, the regular discount activities of e-commerce websites. (For example, a 20% discount on purchasing girlfriends on November 11 is stipulated for Taobao)

Third, update or add data regularly.

Fourth, my friend's birthday. Birthday wishes can be given regularly. Wait a minute (I don't give one example either)

III. Installation of Quartz.NET

The VS version I used was the NuGet package for the NuGet package management-management solution in 2015. Enter the Quartz.NET installation

 

You can also install commands through the NuGet console.

Install-Package Quartz


IV. Quartz.NET Implementation Ideas

First, inherit and implement the IJob interface, write what you want to do in the Execute method (remember)

Second, use the API in Quartz to define work triggers and factories

Third, add visualization (remote management)

Fourth, establish configuration communication.

5. Register with Global. asax Application_Start and start the timing task

 

5. Coding

Among them, JobWork is my defined working file, which contains triggers that already correspond to the work you want to perform (one job corresponds to one trigger).

First, I wrote a trigger for inserting text into a text file (note that what IJob has to inherit must be written in Execute)

 

  public class AddMassagejob : IJob
{
public void Execute(IJobExecutionContext context) { var reportDirectory = string.Format("~/text/{0}/", DateTime.Now.ToString("yyyy-MM-ssss")); reportDirectory = System.Web.Hosting.HostingEnvironment.MapPath(reportDirectory); if (!Directory.Exists(reportDirectory)) { Directory.CreateDirectory(reportDirectory); } var dailyReportFullPath = string.Format("{0}text_{1}.log", reportDirectory, DateTime.Now.Day); var logContent = string.Format("{0}-{1}-{2}", DateTime.Now, "Dripping drop", Environment.NewLine); if (logContent == null) { JobExecutionException jobex = new JobExecutionException("Write failure");
} File.AppendAllText(dailyReportFullPath, logContent); } }
 public class AddMasagerTriggerServer
    {

        public ITrigger AddMasagerTrigger()
        {
            var trigger = TriggerBuilder.Create()
                .WithIdentity("Add messages to logs", "Job Trigger")
                .WithSimpleSchedule(x => x
                    //.WithIntervalInSeconds(5)
                    // .WithIntervalInHours(5)
                    .WithIntervalInMinutes(5) //Execute every five minutes
                    .RepeatForever())
                .Build();
            return trigger;
        }
    }

I've set up a five-minute execution here. You can also ask him to execute it once in five seconds and five hours.

On Time Allocation

Some common official examples

0 12 *? Triggered at 12 o'clock every day
0 1510?** Triggered at 10:15 a.m. a day
0 1510 *? Triggered at 10:15 a.m. a day
0 1510 * *?* Triggered at 10:15 a.m. a day
0 1510 *? Triggered at 10:15 a.m. a day in 2005
0 * 14 *? Triggered every minute from 2:00 p.m. to 2:59 p.m.
0/514*? Every afternoon from 2:00 to 2:59 (starting at the whole point, triggered every five minutes)
0/514, 18* *? Every afternoon from 2:00 to 2:59 (starting at the whole point, triggered every five minutes)
From 18 p.m. to 18:59 p.m. every day (starting at the whole point, triggered every five minutes)
0-514*? Triggered every minute from 2 p.m. to 2.05 p.m.
10,44 14?3 WED Triggered at 2:10 and 2:44 p.m. every Wednesday in March (in exceptional cases, in a time setting, twice or more than twice)
0 592?* FRI triggered at 2:59 a.m. every 5:00 a.m.
01510?* MON-FRI triggers at 10:15 a.m. every day from Monday to Friday.
0 1510 15 *? Triggered at 10:15 a.m. on the 15th of each month
0 15 10 L *? Triggered at 10:15 on the last day of the month
0 1510?* 6L triggers at 10:15 on Friday, the last week of each month.
0 15110?* 6L 2002-2005 triggered at 10:15 on Friday, the last week of each month from 2002 to 2005
0.1510?* 6#3 Triggered on the Friday of the third week of each month.
0 121/5*? Triggered every five days from the first noon of the month.
11 11 11 11 11? Triggered at 11:11 on November 11 every year (Singles Day)

Interested friends can understand the specific meaning of the norms

 

And then create a job where I use generics to create it.

 public class JobServer<T> where T : IJob
    {
        public string JobName { get; set; }
        public string JobGroup { get; set; }

        public IJobDetail CrateJob()
        {
            IJobDetail job1 = JobBuilder.Create<T>() //Create a job
                .WithIdentity(JobName, JobGroup) //JobName  The name of the task on behalf of you. JobGroup Task grouping
                .Build();

            return job1;
        }

    }

Next up are some Quartz configurations (thread configurations, remote configurations, etc.). Of course, you can also choose to write in a configuration file or an XML file.

public class JobBase
    {
        
        public static IScheduler Scheduler
        {
            get
            {
                var properties = new NameValueCollection();

                // Setting up thread pool
                properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
                //Set the maximum number of threads in the thread pool
                properties["quartz.threadPool.threadCount"] = "5";
                //Setting the priority of each thread in the job
                properties["quartz.threadPool.threadPriority"] = ThreadPriority.Normal.ToString();

                // Remote Output Configuration
                properties["quartz.scheduler.exporter.type"] = "Quartz.Simpl.RemotingSchedulerExporter, Quartz";
                properties["quartz.scheduler.exporter.port"] = "1996";  //Configure port number
                properties["quartz.scheduler.exporter.bindName"] = "QuartzScheduler"; 
                properties["quartz.scheduler.exporter.channelType"] = "tcp"; //Protocol type
                
                //Create a factory
                var schedulerFactory = new StdSchedulerFactory(properties);
                //start-up
                var scheduler = schedulerFactory.GetScheduler();

                return scheduler;
            }

        }

        public static void AddSchedule<T>(JobServer<T> jobServer,ITrigger trigger, string jobName, string jobGroup) where T : IJob
        {
            jobServer.JobName = jobName;
            jobServer.JobGroup = jobGroup;
            Scheduler.ScheduleJob(jobServer.CrateJob(), trigger);
} }
 Binding trigger and job

Then on the worklayer, which is the declarative invocation of the task.

 public class JobManager
    {
        public static void State()
        {
            //Open dispatching
            JobBase.Scheduler.Start();

            // The first parameter is what you want to do.(job)  The second parameter is the trigger corresponding to this work.(Trigger)(for example:Execute once in a few seconds or minutes)
            JobBase.AddSchedule(new JobServer<AddMassagejob>(),  
                new AddMasagerTriggerServer().AddMasagerTrigger(),"Write text to the text every five minutes","Message work");

            JobBase.AddSchedule(new JobServer<DiscountedShopJob>(), 
                new DiscountedShopTriggerServer().GoodsDisCountTrigger(),"The last day of the month 10.15 Open discount activities","Discount activities");
        }
    }

Add the following code to the global class to start work

 public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            JobManager.State();
        }
    }

 

The code section has been completed and the next step is how to use it.

First, install a remote management, which is visual operation (you don't need to write any code)

The installation steps are the same.   

Implement installation commands at the console

  PM> Install-Package CrystalQuartz.Remote

 

After installation, you will find such code in web.config

The red box below is where the port number and remote name of Scheduler Host correspond to the configuration in the code above. Once consensus is maintained, communication is achieved. Common

Then start the project by adding / CrystalQuartzPanel.axd to the routing

Okay. It's time to see the effect.

Because personal English is really limited. The name is incorrect. Thank you all.

Posted by stig1 on Mon, 31 Dec 2018 08:21:08 -0800