Quartz solutions that cannot directly use an existing object instance
Because quartz must implement the job interface for all tasks to be performed, and quartz to perform the task by creating a Jobdetail object. In the Jobdetail constructor, only a constructor that uses class as a parameter can not be used directly in the case where an existing instance object is needed, and must be handled by some other means.
Here's a solution:
Myjob.java
Package eg; public class Myjob { public void execute () { Do somthing System.err.println (System.currenttimemillis ()); } } |
The real class that needs to be executed, only one method execute () executes the specific task
Myjobproxy.java
Package eg; Import Org.quartz.Job; Import Org.quartz.JobDataMap; Import Org.quartz.JobExecutionContext; Import org.quartz.JobExecutionException; public class Myjobproxy implements job{ Private Myjob job = null; public void execute (jobexecutioncontext context) throws Jobexecutionexception { Jobdatamap Jobdatamap = Context.getjobdetail (). Getjobdatamap (); This.job = (myjob) jobdatamap.get ("Myjob"); This.job.execute (); } } |
A proxy class used to execute the Myjob Execute method. This class implements the job interface, and in the Execute method you need to get a real Myjob class instance from Jobexecutioncontext and then execute the Myjob Execute method.
Test.java
package eg; Import java.util.Date; Import Org.quartz.JobDetail; Import Org.quartz.Scheduler; Import org.quartz.SchedulerFactory; Import Org.quartz.SimpleTrigger; Import org.quartz.TriggerUtils; Import org.quartz.impl.StdSchedulerFactory; Public class Test { public static void Main (string[] args) throws Exception { Schedulerfactory SF = new STDSC Hedulerfactory (); Scheduler sched = Sf.getscheduler (); Jobdetail jobdetail = new Jobdetail ("Job1", "group1", Myjobproxy.class); Jobdetail.getjobdatamap (). Put ("Myjob", New Myjob ()); Simpletrigger trigger = new Simpletrigger ("Trigger1", "group1", new Date (triggerutils.getnextgivenseconddate null , 1). GetTime ()); Sched.schedulejob (jobdetail, trigger); Sched.start (); Thread.Sleep (5000); Sched.shutdown (); } } |
This is a test class that first gets the scheduler object and then constructs the Jobdetail instance, Jobdetail jobdetail = new Jobdetail ("Job1", "group1", Myjobproxy.class), Note that the Myjobproxy class is used as a parameter, and the Jobdetail.getjobdatamap () is used after construction. Put ("Myjob", New Myjob ()) to join our existing Myjob object instance, In order to simply use a new Myjob object, in the Myjobproxy.execute () method you will get the Myjob object that you just created, and then drop the Myjob.execute () method to perform the specific task.