Quartz cannot directly use existing object instances
Because Quartz must implement the Job interface for all tasks to be executed, and Quartz creates a JobDetail object to execute the task. In the JobDetail constructor, only the constructor that uses Class for parameters is provided. Therefore, you cannot directly use existing instance objects, you must use other methods.
The following is a solution:
MyJob. java
Package eg; Public class MyJob { Public void execute (){ // Do somthing System. err. println (System. currentTimeMillis ()); } } |
Only one method execute () is used to execute specific tasks.
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.exe cute (); } } |
A proxy class used to execute the execute method of MyJob. This class implements the Job interface, and obtains a real MyJob class instance from JobExecutionContext in the execute method, and then executes the execute method of MyJob.
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 StdSchedulerFactory (); 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. first obtain the Scheduler object, and then construct the JobDetail instance, JobDetail jobDetail = new JobDetail ("job1", "group1", MyJobProxy. class). Note that the MyJobProxy class is used as the parameter. After the construction, jobDetail is used. getJobDataMap (). put ("myjob", new route cute () method to execute a specific task.