Scheduled execution tasks based on ASP.NET MVC (C#) and Quartz.Net components

Scheduled execution tasks based on ASP.NET MVC (C#) and Quartz.Net components

In the previous articles " Recommend a simple, lightweight, and very powerful C#/ASP.NET timing task execution manager component-FluentScheduler " and " Simple, lightweight, and very powerful C#/ASP.NET timing task execution In "Management Components-FluentScheduler's Examples ", we know and understand FluentScheduler, a lightweight timing task scheduling execution component. Today, I will introduce you a component about timing task scheduling and execution-Quartz.Net. Quartz.Net is the .NET implementation of Quartz for Java.

Compared with FluentScheduler, which implements timing scheduling tasks, the use of simple and less configuration features, Quartz.Net configuration is slightly more complicated. Below we will join a small example of debugging the timing execution task of ASP.NET MVC website application to understand the simple usage of Quartz.Net. Of course, Webform web applications can also use Quartz.Net for timing tasks.

1. we open Visual Studio 2015 and create an ASP.NET MVC web application project named QuartzNetMvcDemo :

Then install Quartz.Net components through the package manager console as follows:

One of the simplest tasks of Quartz.Net includes at least three parts of realization: job (job), trigger (trigger) and scheduler (scheduler). The job is the business logic that you need to execute in a timed task. The trigger specifies when and according to which rules the job will be executed. Finally, the job and trigger will be registered in the scheduler. The scheduler is responsible for coordinating the job and the trigger. Run.

In Quartz.Net, a job (job) is a class. In order for the job to be executed in the Quartz.Net system, we must implement the Execute method of the IJob interface provided by Quartz.Net, such as the IJob implemented in this example. Interface ReportJob class:

using System;
using Quartz;
using System.IO;

namespace QuartzNetMvcDemo
{
  public class ReportJob: IJob
  {
    public void Execute(IJobExecutionContext context)
    {
      var reportDirectory = string.Format("~/reports/{0}/", DateTime.Now.ToString("yyyy-MM"));
      reportDirectory = System.Web.Hosting.HostingEnvironment.MapPath(reportDirectory);
      if (!Directory.Exists(reportDirectory))
      {
        Directory.CreateDirectory(reportDirectory);
      }
      var dailyReportFullPath = string.Format("{0}report_{1}.log", reportDirectory, DateTime.Now.Day);
      var logContent = string.Format("{0}==>>{1}{2}", DateTime.Now, "create new log.", Environment.NewLine);
      File.AppendAllText(dailyReportFullPath, logContent);
    }
  }
}

The Execute method has an IJobExecutionContext interface object as a parameter. This parameter contains the configuration information of the job that defines this class. Of course, as an example, in this example, we did not use this parameter.

Next, we need to implement a trigge (trigger), the sample code is as follows:

using Quartz;
using Quartz.Impl;

namespace QuartzNetMvcDemo
{
  public class ReportJobScheduler
  {
    public static void Start()
    {
      IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
      scheduler.Start();
      IJobDetail job = JobBuilder.Create<ReportJob>().Build();
      ITrigger trigger = TriggerBuilder.Create()
        .WithIdentity("triggerName", "groupName")
        .WithSimpleSchedule(t =>
          t.WithIntervalInSeconds(5)
           .RepeatForever())
           .Build();

      scheduler.ScheduleJob(job, trigger);
    }
  }
}

You can put this code snippet anywhere in your project program that can be called, and you can take the class name at will, it doesn't matter. Just quote it correctly when using this class.

In the code, we use StdSchedulerFactory.GetDefaultScheduler() to create a scheduler (scheduler) and then start the scheduler, and then create a simple Quartz.Net trigger and configure this trigger: Specify The name of the trigger is triggerName, and the group of the trigger is groupName, which specifies that it will trigger once every 5 seconds and it will always be triggered in a loop. Finally, the job (job) and trigger (trigger) are registered in the scheduler through the scheduler.ScheduleJob() method, so that a complete timing task is customized.

Finally, one thing we have to do is to start our customized timing task. We put this task in the Application_Start method of the global cs file (Global.asax) of the project program to execute:

using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace QuartzNetMvcDemo
{
  public class MvcApplication: System.Web.HttpApplication
  {
    protected void Application_Start()
    {
      AreaRegistration.RegisterAllAreas();
      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
      RouteConfig.RegisterRoutes(RouteTable.Routes);
      BundleConfig.RegisterBundles(BundleTable.Bundles);
      
     //Start timing task
      ReportJobScheduler.Start();
    }
  }
}

Ok, now all operations are completed, press F5 to run our ASP.NET MVC timing task scheduling execution sample program. After a minute to open our log file, if the program runs normally, then you will see the following log:

How about, is the timing execution task scheduling implemented by Quartz.Net relatively simple? Of course, this is just a simple example of Quartz.Net. Quartz.Net also has many more advanced functions, such as job scheduling that supports configuration files, and job cycle support for cron.

If you think this article is useful to you, please click "Recommend", so that you can help others more effectively! ! !

Reference: https://cloud.tencent.com/developer/article/1034505 Scheduled execution task scheduling based on ASP.NET MVC (C#) and Quartz.Net components-Cloud + Community-Tencent Cloud