Simple Tasks for Quartz.net Timing Tasks

Posted by Pegasys on Sat, 29 Jun 2019 00:21:59 +0200

I. Overview

1. quartz.net is a timing task framework that extends from java quartz.   

2. I saw a lot of great gods on the Internet wrote blogs and articles about quartz.net, and learned a lot about quartz in these blog articles. Today, the blogger also wants to write an article about quartz, hoping to help his brothers and sisters who are learning quartz and consolidate themselves by the way.

3. quartz blog will start from the most basic, and then will gradually upgrade. If you like brothers and sisters, please pay attention to my blog, the blogger will keep updating.

II. Construction

1. Open vs to create a new mvc empty project named Quartz mvc as shown in Figure 1

  

2. Complete the previous step, and then we will install quart

(1) Open the Visual Tool - > Library Package Manager - > Package Management Desk. Enter after opening the Package Management Desk.

  

(2) After successful installation, you will see an additional job_scheduling_data_2_0.xsd file in the project (no need to pay attention to it)

  

3. In step 2, we successively installed log4net.dll, Common.Logging.dll, Common.Logging.Core.dll.

(1) Installed as follows

  

4. Configure web.config and add the log output path as shown in the figure.

  

III. Code

1. Add a controller named Home

(1) Add a view Index to the Home controller

(2) Create a log tool class under the QuartzMVC project named LogTool and write the following code

 1         public static void DetailLogRecord(string type, LogTool.FolderCreationType folderCrationType, string content, bool isErasable, string filename = null)
 2         {
 3             string folderPrefixPath = (System.Configuration.ConfigurationManager.AppSettings["localLogPath"] ?? "c:\\test_log_tem") + "\\" + type;
 4             string folderPath = "";
 5             try
 6             {
 7                 switch (folderCrationType)
 8                 {
 9                     default: folderPath = folderPrefixPath; break;
10                 }
11                 if (!Directory.Exists(folderPath))
12                 {
13                     Directory.CreateDirectory(folderPath);
14                 }
15                 string filePath = folderPath + "\\" + (filename ?? DateTime.Now.ToString("yyyyMMdd")) + ".log";
16                 content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "  :\r\n" + content + "\r\n";
17                 if (isErasable) LogTool.RecordNewFileLog(filePath, content);
18                 else LogTool.RecordConsecutiveLog(filePath, content);
19             }
20             catch
21             {
22                 throw;
23             }
24 
25         }
26 
27 
28         public enum FolderCreationType
29         {
30             None
31         }
32 
33         private static void RecordConsecutiveLog(string filePhysicalUrl, string pursuitContent)
34         {
35             System.IO.FileStream fs = new System.IO.FileStream(filePhysicalUrl, FileMode.OpenOrCreate, FileAccess.Write);
36             System.IO.StreamWriter m_streamWriter = new System.IO.StreamWriter(fs);
37             m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
38 
39             string resultStr = Environment.NewLine + pursuitContent;
40 
41             m_streamWriter.WriteLine(resultStr);
42             m_streamWriter.Flush();
43             m_streamWriter.Close();
44             fs.Close();
45         }
46 
47         private static void RecordNewFileLog(string filePhysicalUrl, string content)
48         {
49             System.IO.StreamWriter sw = new System.IO.StreamWriter(filePhysicalUrl);
50             sw.WriteLine(content);
51             sw.Close();
52         }
53 
54         private static void CreateFolder(string url)
55         {
56             if (Directory.Exists((url)) == false)
57             {
58                 Directory.CreateDirectory((url));
59             }
60         }

(3) Open the View Index and add the following code

1 @using (Html.BeginForm("FirstQuartz", "Home", FormMethod.Post))
2 {
3     <input type="submit"  value="Click to open the first timed task"/>
4 }

(4) Create a JobClass class under the Model folder under the QuartzMVC project and inherit the IJob interface code as follows

 1 public class JobClass:IJob
 2     {
 3          //Journal
 4          private static ILog _log = LogManager.GetLogger(typeof(JobClass));
 5 
 6         /// <summary>
 7         /// Construction method
 8         /// </summary>
 9          public JobClass()
10         { }
11         /// <summary>
12         ///  Job default interface  
13         /// </summary>
14         /// <param name="context"></param>
15         public void Execute(IJobExecutionContext context)
16         {
17             LogTool.DetailLogRecord("a", LogTool.FolderCreationType.None, "My first task", false);
18         }
19     }

(5) Open the Home Controller Add Method "FirstQuartz" as follows

 1 public void FirstQuartz()
 2         {
 3             StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();
 4             //Get Scheduled
 5             IScheduler sched = schedulerFactory.GetScheduler();
 6             //Construct a dispatching plant
 7             LogTool.DetailLogRecord("a", LogTool.FolderCreationType.None, "Create Scheduler Successfully", false);
 8             sched.Start();
 9 
10             IJobDetail job = JobBuilder.Create<JobClass>()
11                     .WithIdentity("Job Name", "Job grouping")
12                     .Build();
13                 // Trigger job
14                 ITrigger trigger = TriggerBuilder.Create()
15 
16                 #region Use time interval is not introduced 
17                     //.WithIdentity("myTrigger", "group1")
18                     //.StartNow()
19                     //.WithSimpleSchedule(x => x
20                     //    .WithIntervalInSeconds(5)
21                     //    .RepeatForever())
22                     //.Build();
23                 #endregion
24 
25                 #region Use cron rule
26 
27                     .WithIdentity("Trigger Name", "Trigger grouping")
28                     .WithCronSchedule("/5 * * ? * *") // Executing this expression every five seconds will be introduced in the next article.
29                     .StartAt(DateTime.UtcNow)
30                     .WithPriority(1)
31                     .Build();
32                 #endregion
33                 // Add jobs and triggers to the scheduler
34                 sched.ScheduleJob(job, trigger);
35 
36             // 2 Close Job Scheduling Timely Close Task Example  
37             //Thread.Sleep(TimeSpan.FromDays(2));
38 
39             //   _sched.Shutdown(); // End
40         }

(5) Our first simple quartz task will be completed here.

2. There are only methods for opening tasks, but no methods for closing tasks. You can add them freely if you need to.

(1) The closing method is _sched.Shutdown(), which is annotated at the end of the opening method and can be separated by the reader.

IV. Testing

1. Running the project will see the following page

  

(1) Click the button to open the task.

(2) Open the local disk e. You will see a folder QuartzLog with a log file that is your task record as shown in the figure.

  

(3) We can see that tasks are performed every five seconds that we define.

V. Source Code and Description

1. Source address: http://git.oschina.net/yangguangchenjie/quartzmvc

2. If you like my article, please pay attention to O(________________

Topics: C# Java git