Quartz Lesson 3: More About Jobs & amp; JobDetails (official document translation), quartzjobs

Source: Internet
Author: User

Quartz Lesson 3: More About Jobs & JobDetails (official document translation), quartzjobs

After completing the second lesson, you are delighted to find that it is quite simple to make jobs work. Although it is easy to run jobs, you still need to know the key content of its execution. They are Execute and JobDetails in the IJob interface.

 

When you define a class that implements the IJob interface, you need to implement the actual code in it. Quartz. NET needs to know various information about the code so that Quartz. NET can work as expected. These details are described in the JobDetail class and briefly described in the previous section.

 

JobDetail is instantiated by JobBuilder. JobBuilder allows developers to use fluent interface. to customize JobDetail details.

 

Let's take a moment to look at the Job mechanism and its lifecycle in Quartz. NET. Let's take a look at the example we have seen in section 1:

1 // define the job and tie it to our HelloJob class 2 IJobDetail job = JobBuilder. create <HelloJob> () 3. withIdentity ("myJob", "group1") 4. build (); 5 6 // Trigger the job to run now, and then every 40 seconds 7 ITrigger trigger = TriggerBuilder. create () 8. withIdentity ("myTrigger", "group1") 9. startNow () 10. withSimpleSchedule (x => x11. withIntervalInSeconds (40) 12. repeatForever () 13. build (); 14 15 sched. scheduleJob (job, trigger );View Code

Now defineHelloJobAs follows:

1 public class HelloJob : IJob2 {3     public void Execute(IJobExecutionContext context)4     {5         Console.WriteLine("HelloJob is executing.");6     }7 }

Note that an IJobDetail instance is provided for scheduler, which can run only one job instance. When schedute executes a job, scheduler instantiates a job instance before calling the Execute method. The premise for job instantiation is that a constructor without parameters is required in the job class. It is worth noting that defining any data fields in the job class does not make much sense, because these data fields are not retained during job operation.

 

How can I provide attributes and configuration information for a job? In addition, Can we track and maintain the job execution status? To answer these questions, you must understand JobDataMap, which is part of JobDetail.

 

JobDataMap

JobDataMapWhich can be used to accommodate any quantity you want to provideJobThe object that can be serialized during execution of the instance.JobDataMapImplementedIDictionaryInterface, and added some practical methods for storing and retrieving basic types of data.

 

Below isJobDataMap Quick Start code: add some data to JobDataMap before adding a job to scheduler:

1 // define the job and tie it to our DumbJob class2 IJobDetail job = JobBuilder.Create<DumbJob>()3     .WithIdentity("myJob", "group1") // name "myJob", group "group1"4     .UsingJobData("jobSays", "Hello World!")5     .UsingJobData("myFloatValue", 3.141f)6     .Build();

The following isJob.JobDataMap data

 1 Getting Values from a JobDataMap 2 public class DumbJob : IJob 3 { 4     public void Execute(JobExecutionContext context) 5     { 6       JobKey key = context.JobDetail.Key; 7  8       JobDataMap dataMap = context.JobDetail.JobDataMap; 9 10       string jobSays = dataMap.GetString("jobSays");11       float myFloatValue = dataMap.GetFloat("myFloatValue");12 13       Console.Error.WriteLine("Instance " + key + " of DumbJob says: " + jobSays + ", and val is: " + myFloatValue);14     }15 }

If you are going to use a persistent JobStore (JobStore will be discussed in the JobStore Section), you should focus on what will be placed in JobDataMap. Because it will be serialized, it is more prone to version problems. It is safe in standard versions, and anyone else can change your entity class. Therefore, you have to worry about the possibility that compatibility will be compromised.

 

Therefore, you can put AdoJobStore and JobDataMap into map, which only contains the original function and string data, thus eliminating various serialization problems.

 

Because Quartz's default JobFactory will go to the instance with the set attribute when the job is instantiated, therefore, when you add a property with set access, the corresponding key will be created in JobDataMap to save it. In this way, do not map the display area in the execute method.

 

TriggerThere are also relatedJobDataMap. When you need multipleTriggerScheduling and repetitionScheduler this is very useful. Each Trigger is independent and requires you to enter configuration information separately.

 

JobDataMap uses JobExecutionContext as the context during job execution. It contains JobDataMap and Trigger and overwrites the previous same value.

 

The following is fromJobExecutionContextTheJobDataMapA simple example:

1 public class DumbJob: IJob 2 {3 public void Execute (IJobExecutionContext context) 4 {5 JobKey key = context. jobDetail. key; 6 7 JobDataMap dataMap = context. mergedJobDataMap; // Note the difference from the previous example 8 9 string jobSays = dataMap. getString ("jobSays"); 10 float myFloatValue = dataMap. getFloat ("myFloatValue"); 11 IList <DateTimeOffset> state = (IList <DateTimeOffset>) dataMap ["myStateData"]; 12 state. add (DateTimeOffset. utcNow); 13 14 Console. error. writeLine ("Instance" + key + "of DumbJob says:" + jobSays + ", and val is:" + myFloatValue); 15} 16}
View Code

Or, if you want to rely onJobFactory"Injection"Data is mapped to your class, which may look like this:

1 public class DumbJob: IJob 2 {3 public string JobSays {private get; set;} 4 public float FloatValue {private get; set;} 5 6 public void Execute (IJobExecutionContext context) 7 {8 JobKey key = context. jobDetail. key; 9 10 JobDataMap dataMap = context. mergedJobDataMap; // Note the difference from the previous example11 12 IList <DateTimeOffset> state = (IList <DateTimeOffset>) dataMap ["myStateData"]; 13 state. add (DateTimeOffset. utcNow); 14 15 Console. error. writeLine ("Instance" + key + "of DumbJob says:" + JobSays + ", and val is:" + FloatValue); 16} 17}View Code

You will notice that the entire code of the class is long,Execute() The method code is clean. It can also be argued that although the code is longer, it actually takes less coding if the programmer'sIDEThis API is used to automatically generate attributes without having to manually write a separate call fromJobDataMap.This is your choice.

Job "Instances"

Many users are confused about what constitutes"JobInstance ". We will try our best to clarify the following sections about the working status and concurrency.

 

You can createJobAnd createJobDetailsMultiple instances are stored in the scheduling"Instance Definition"-Each has its own attributes andJobDataMap-And they are all addedScheduler

 

For example, you can create an implementationSalesReportJob"OfIJobInterface Class. ThisJobIt may be sent to it after the code expires.JobDataMapTo specify the sales report according to the name and parameters of the sales personnel. Then they can create multiple definedJob(JobDetails), Such"SalesReportForJoe"And"SalesReportForMike"With"JoeJoe"And"Mike"In the correspondingJobDataMapsAs input to their respectiveJob.

 

WhenTriggerStartJobDetail(Instance definition), it will be automatically loaded, andJobBy configuringJobFactoryInstantiation. DefaultJobFactoryOnly call and useActivator. CreateInstanceCallJobClass default constructor, and then tryJobDataMapInSetterAttribute. You may want to create your ownJobFactoryFor exampleIoCOrDIContainer generation/Initialize a job instance.

 

In "Quartz speak", we refer to each stored JobDetail as "job definition" or "JobDetail instance ", we mean that each execution job acts as a "job instance" or "job-defined instance ". Generally, if we only use the word "job", we mean a definition or JobDetail. When we refer to the class to implement the job interface, we usually use the term "job type ".

Job State and Concurrency

For more information, seeJobStatus data (Aka JobDataMap) And concurrency additional description. You can combine the features of tianjian to yourJobClass to influenceQuartz'.

 

DisallowConcurrentExecutionAddJobClass, tellQuartzDo not execute the givenJobDefines multiple instances (that is, the givenJobClass) Concurrent attributes. Note that you must use it with caution. In the example in the previous section, ifSalesReportJob"With this attribute, there is only one"SalesReportForJoe"The instance can be executed at a given time, but it can be"SalesReportForMike". The constraint is based on an instance definition (JobDetailAnd so on. However, it (QuartzDesign), determines the attributes carried by the class itself, because it determines how to compile the class.

 

PersistJobDataAfterExecutionYes can be addedJobClass, tellQuartzUpdateJobDetailOfJobDataMapThe stored copy attributes are inExecute() After the method is successfully completed (no exception is thrown), make the sameJobThe next execution (JobDetail), Instead of the updated value of the previously stored value. ImageDisallowConcurrentExecutionAttribute, which applies to job-defined instances, rather than job-class instances.JobClass attributes, because it often makes the difference in how the class is encoded (such'Stateful'Explicitly"Understanding").

 

If you use the PersistJobDataAfterExecution attribute, you should carefully consider using the DisallowConcurrentExecution attribute to avoid confusion (competition condition) between the two instances of the same job (JobDetail) when leaving any data)

Other Attributes Of Jobs

The following isJobDetailAnd other objectsJobSummary of other attributes defined by instances:

 

Durability-IfJobIt is not persistent and will be automatically deleted from scheduling. Once there is no trigger related to any activity. In other words, non-persistentJobIt has a life limit triggered by it.

Recoverability-If the job"Recovery required"It is in the scheduling"Hard close"And then run it again when the scheduler starts again. In this case,JobExecutionContext. RecoveringProperty returns true.

JobExecutionException

Finally, we need to tell youIJob. Execute(... The unique type that you should throw from the execution method isJobExecutionException. Because of this, you should changeExecuteAll content of the method is'OfTry-catch"Block. You should also spend some time readingJobExecutionExceptionDocumentation, you can use it to provide scheduling instructions for how you want to handle exceptions.

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.