Simple tasks for Quartz.net scheduled tasks and simple tasks for quartz.net

Source: Internet
Author: User

Simple tasks for Quartz.net scheduled tasks and simple tasks for quartz.net
I. Overview

1. quartz.net is a scheduled task framework extended from java quartz.

2. I have seen many blogs and articles about quartz.net on the internet, and I have learned a lot about quartz in these blog articles. Today, bloggers also want to write an article about quartz (I hope you can understand the shortcomings), hoping to help the brothers and sisters who are learning quartz and consolidate themselves by the way.

3. The Z blog will be updated gradually from the very beginning. If you have any siblings, please pay attention to my blog. The blog will be updated continuously.

Ii. Construction

  1. Open vs and create a new empty mvc project named QuartzMVC.

  

 2. Complete the previous step. Next we will install quart.

(1) Open the vs tool --> Program Package Manager --> package console open the package console and enter

  

(2) After the installation is successful, you will see an additional job_scheduling_data_2_0.xsd file in the project (ignore this)

  

3. in step 3, we have installed three log tools: log4net. dll, Common. Logging. dll, and Common. Logging. Core. dll.

(1) installation is as follows:

  

 4. Configure web. config and add the log output path

  

Iii. Code

  1. Add a controller named Home

(1) Add a View Index to the Home controller.

(2) create a log tool class name under the QuartzMVC project: 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             catch21             {22                 throw;23             }24 25         }26 27 28         public enum FolderCreationType29         {30             None31         }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         }
View Code

(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 enable the first scheduled task"/> 4}
View Code

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

1 public class JobClass: IJob 2 {3 // log 4 private static ILog _ log = LogManager. getLogger (typeof (JobClass); 5 6 /// <summary> 7 /// constructor 8 /// </summary> 9 public JobClass () 10 {} 11 // <summary> 12 // default job 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}
View Code

(5) Open the Home controller and add the method "FirstQuartz" as follows:

1 public void FirstQuartz () 2 {3 StdSchedulerFactory schedulerFactory = new StdSchedulerFactory (); 4 // get scheduling 5 IScheduler sched = schedulerFactory. getScheduler (); 6 // construct a scheduling factory 7 LogTool. detailLogRecord ("a", LogTool. folderCreationType. none, "scheduler created successfully", false); 8 sched. start (); 9 10 IJobDetail job = JobBuilder. create <JobClass> () 11. withIdentity ("job name", "job group") 12. build (); 13 // trigger job 14 ITrigger trigger = TriggerBuilder. create () 15 16 # region use interval first not to introduce 17 //. withIdentity ("myTrigger", "group1") 18 //. startNow () 19 //. withSimpleSchedule (x => x20 //. withIntervalInSeconds (5) 21 //. repeatForever () 22 //. build (); 23 # endregion24 25 # region uses cron rules 26 27. withIdentity ("trigger name", "trigger Group") 28. withCronSchedule ("/5 **? ** ") // Execute this expression every five seconds. We will introduce this expression in the next article 29. startAt (DateTime. utcNow) 30. withPriority (1) 31. build (); 32 # endregion33 // Add the job and trigger to scheduler 34 sched. scheduleJob (job, trigger); 35 36 // close job Scheduling in 2 days. Close job instance 37 // Thread. sleep (TimeSpan. fromDays (2); 38 39 // _ sched. shutdown (); // end 40}
View Code

(5) Here we have built the first simple quartz task.

2. Only the method to enable the task is provided here, and no method to disable the task is provided. You can add the task as needed.

   (1) The close method is _ sched. Shutdown (), which is finally commented out in the Enable method. Readers can separate the methods separately.

Iv. Test

  1. Run the project and you will see the page shown in figure

  

(1) click the button to enable the task.

(2) Open the local disk e and you will see a log file in the QuartzLog folder, which is your task record.

  

(3) We can see that the task is executed once every five seconds as defined.

V. source code and description

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

  2. If you like my article, pay attention to O (∩ _ ∩) O ~~ , Leave a message if you have any questions.   

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.