Getting started with Quartz

Keywords: Attribute Java Maven JDBC

1, About Quartz

1.quartz is an open source and rich "task scheduling library", which can be integrated into any java application.

2.quartz is mainly divided into three components: task Job, Trigger trigger and Scheduler.

quartz architecture:

 

2, Introduction to the three components of quartz

1. Task Job: the task class you want to call. You need to implement the org.quartz.job interface and override the execute() method. The execute() method will be executed during task scheduling.

2. Trigger trigger: that is, the trigger to execute tasks. When what conditions are met, it will execute your task Job. It is mainly divided into simple trigger executed according to the time interval and CronTrigger executed according to the calendar.

3. Scheduler: after the Trigger is bound to the Job, it is the component responsible for Job scheduling according to the settings in the Trigger.

 

3, Case introduction

1. Introduce maven:

        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.3.2</version>
        </dependency>

        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz-jobs</artifactId>
            <version>2.3.2</version>
        </dependency>

This article uses version 2.3.2. It is recommended to use the latest version. If you need logs, you can import them by yourself.

2. Test code:

public class QuartzTest {


    public static void main(String[] args) throws SchedulerException {
        //1. Scheduler
        SchedulerFactory schedulerfactory = new StdSchedulerFactory();
        //Get the scheduler, the scheduler only needs one, can schedule multiple tasks
        Scheduler scheduler = schedulerfactory.getScheduler();
        //2.Job instance (JobDetil)
        JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
                .withIdentity("job", "default") //Name: task name, group: group name
                .build();
        //3. Trigger
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger", "default") //Name: trigger name, group: group name
                .startNow() //Do it now, default
                .withSchedule(SimpleScheduleBuilder.repeatSecondlyForTotalCount(20,2))//Use Simple trigger, execute 20 times, every 2 seconds
                .build();
        //4. Associate Job with trigger
        scheduler.scheduleJob(jobDetail,trigger);
        //5. Schedule tasks
        scheduler.start();
        //Let the main thread block, easy to test
        Thread.yield();
    }

    
    public static class MyJob implements Job {
        
        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            //Print current time
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = dateFormat.format(new Date());
            System.out.println(date);
        }
    }
}

3. Implementation results:

Print time every two seconds.

3. Step description:

From the above, we can know that the operation of quartz can be roughly divided into six steps:

1. Get a task Scheduler through SchedulerFactory

2. Implement the org.quartz.job interface, and rewrite the execute() method to schedule the tasks that you need.

3. Build a Job detail (Job instance object) through JobBuilder.newJob(), and set corresponding parameters.

4. Build a Trigger trigger through TriggerBuilder.newTrigger(), and set the corresponding parameters.

5. Bind JobDetail and Trigger through the Scheduler.

6. Start the task scheduling through the start() method of the Scheduler.

 

4, Parameter passing

1. Test code:

public class QuartzTest {


    public static void main(String[] args) throws SchedulerException{
        //1. Scheduler
        SchedulerFactory schedulerfactory = new StdSchedulerFactory();
        //Get the scheduler, the scheduler only needs one, can schedule multiple tasks
        Scheduler scheduler = schedulerfactory.getScheduler();
        //2.Job instance (JobDetil)
        JobDataMap jobDetailMap = new JobDataMap();
        jobDetailMap.put("name","xuye");
        JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
                .withIdentity("job", "default") //Name: task name, group: group name
                .usingJobData(jobDetailMap) //Transfer parameters
                .build();
        //3. Trigger
        JobDataMap triggerMap = new JobDataMap();
        triggerMap.put("age",100);
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger", "default") //Name: trigger name, group: group name
                .usingJobData(triggerMap)
                .startNow() //Do it now, default
                .withSchedule(SimpleScheduleBuilder.repeatSecondlyForTotalCount(1,2))//Use Simple trigger, execute once, every 2 seconds
                .build();
        //4. Let scheduler associate Job and trigger
        scheduler.scheduleJob(jobDetail,trigger);
        scheduler.start();
        //Block the current thread for testing
        Thread.yield();
    }

    public static class MyJob implements Job {



        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            //Method 1: get all the parameter information passed by JobDetail and Trigger. You can't set a value with this method.
            JobDataMap jobDataMap = jobExecutionContext.getMergedJobDataMap();
            //Method 2: get the Map parameter of JobDetail
            JobDataMap jobDetailMap = jobExecutionContext.getJobDetail().getJobDataMap();
            //Mode 3: get the Trigger's Map parameter
            JobDataMap triggerMap = jobExecutionContext.getTrigger().getJobDataMap();
            System.out.println("getMergedJobDataMap()Methods key and value: \n"+getKeyAndValue(jobDataMap));
            System.out.println("getJobDetail().getJobDataMap()Methods key and value: \n"+getKeyAndValue(jobDetailMap));
            System.out.println("getTrigger().getJobDataMap()Methods key and value: \n"+getKeyAndValue(triggerMap));
        }

        private String getKeyAndValue(Map<String,Object> map) {
            StringBuilder sb = new StringBuilder();
            Set<Map.Entry<String, Object>> entries = map.entrySet();
            for(Map.Entry<String, Object> entry : entries) {
                sb.append(entry.getKey()+":"+entry.getValue().toString()+",");
            }
            return sb.toString();
        }
    }
}

2. Implementation results:

3. Description:

1. by using JobDataMap objects, the usingJobData method is invoked in JobBuilder and TriggerBuilder to set JobDataMap in.

2. In the org.quartz.job implementation class, obtain the corresponding parameters through the above environment of JobExecutionContext, mainly including the following three methods,

        1)jobExecutionContext.getMergedJobDataMap():

Get the Map parameters of JobBuilder and TriggerBuilder. Note that this method can only get values, not set values, because it is invalid.

        2)jobExecutionContext.getJobDetail().getJobDataMap():

Get the Map parameter of JobDetail. Only JobDetail can be obtained.

        3)jobExecutionContext.getTrigger().getJobDataMap():

Get Trigger's Map parameter, only Trigger's.

3. Suggestion: if you only get the value, use jobExecutionContext.getMergedJobDataMap(), if you need to get the value and pass it to the next task schedule, please use the corresponding parameter of JobDetail or Trigger.

4.jobExecutionContext.getMergedJobDataMap() can't set the principle description: each time a task is scheduled, a JobExecutionContext will be created, and after the creation, all the corresponding parameters of JobDetail or Trigger will be set to a new Map. If the value is set, the next time a Map is created, the setting of the previous JobExecutionContext will become invalid.

 

5, JobDataMap persistence

1. Test code:

public class QuartzTest {

    public static void main(String[] args) throws SchedulerException{
        //1. Scheduler
        SchedulerFactory schedulerfactory = new StdSchedulerFactory();
        //Get the scheduler, the scheduler only needs one, can schedule multiple tasks
        Scheduler scheduler = schedulerfactory.getScheduler();
        //2.Job instance (JobDetil)
        JobDataMap jobDetailMap = new JobDataMap();
        jobDetailMap.put("count",0);
        JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
                .withIdentity("job", "default") //Name: task name, group: group name
                .usingJobData(jobDetailMap) //Transfer parameters
                .build();
        //3. Trigger
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger", "default") //Name: trigger name, group: group name
                .startNow() //Do it now, default
                .withSchedule(SimpleScheduleBuilder.repeatSecondlyForTotalCount(20,2))//Use Simple trigger, execute 20 times, every 2 seconds
                .build();
        //4. Let scheduler associate Job and trigger
        scheduler.scheduleJob(jobDetail,trigger);
        scheduler.start();
        //Block the current thread for testing
        Thread.yield();
    }

    public static class MyJob implements Job {
        
        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            //Get the Map parameter of JobDetail
            JobDataMap jobDetailMap = jobExecutionContext.getJobDetail().getJobDataMap();
            Integer count = (Integer) jobDetailMap.get("count");
            ++count;
            System.out.println("Current execution times:"+count);
            jobDetailMap.put("count",count);
        }

    }
}

2. Implementation results:

3. Description:

1. We want to count the execution times, but the JobDetail parameter Map obtained each time is new.

2. If you want the Map parameters of JobDetail and Trigger to be persistent, just add @ PersistJobDataAfterExecution to the class of the Job instance.

3. Amend as follows:

4. New test results:

5. The effect of JobDetail and Trigger is the same, and Trigger code is not written much. If you use jobExecutionContext.getMergedJobDataMap(), you can only get the Map data of JobDetail and Trigger, but not set values. The principle has been explained above, and you can test it yourself.

 

6, Automatic injection

1. Test code:

public class QuartzTest {

    public static void main(String[] args) throws SchedulerException{
        //1. Scheduler
        SchedulerFactory schedulerfactory = new StdSchedulerFactory();
        //Get the scheduler, the scheduler only needs one, can schedule multiple tasks
        Scheduler scheduler = schedulerfactory.getScheduler();
        //2.Job instance (JobDetil)
        JobDataMap jobDetailMap = new JobDataMap();
        jobDetailMap.put("name","xuye");
        JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
                .withIdentity("job", "default") //Name: task name, group: group name
                .usingJobData(jobDetailMap) //Transfer parameters
                .build();
        //3. Trigger
        JobDataMap triggerMap = new JobDataMap();
        triggerMap.put("age",100);
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger", "default") //Name: trigger name, group: group name
                .usingJobData(triggerMap)
                .startNow() //Do it now, default
                .withSchedule(SimpleScheduleBuilder.repeatSecondlyForTotalCount(1,2))//Use Simple trigger, execute once, every 2 seconds
                .build();
        //4. Let scheduler associate Job and trigger
        scheduler.scheduleJob(jobDetail,trigger);
        scheduler.start();
        //Block the current thread for testing
        Thread.yield();
    }
    
    public static class MyJob implements Job {

        private String name;
        
        private Integer age;

        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            System.out.println("name:"+name+",age: "+age);
        }

        public void setName(String name) {
            this.name = name;
        }
        
        public void setAge(Integer age) {
            this.age = age;
        }
    }
}

2. Implementation results:

  

3. Description:

1. To use auto injection, you only need to provide the set method of the corresponding property name in the org.quartz.job implementation class.

 

7, Common API

1.StdSchedulerFactory

    

Method name Explain
Scheduler getScheduler()
Get a scheduler
Scheduler
void initialize(Properties props)
Initialize SchedulerFactory
Collection<Scheduler> getAllSchedulers()
Get all schedulers

2.Scheduler

Method name Explain
Date scheduleJob(JobDetail jobDetail, Trigger trigger)
Bind JobDetail and Trigger
void triggerJob(JobKey jobKey)
Execute a Job immediately through JobKey
void triggerJob(JobKey jobKey, JobDataMap data)
Execute a Job immediately through JobKey and pass parameters
void start()
Start scheduling all tasks, and restart if called.
void shutdown()
Close all tasks now
void shutdown(boolean waitForJobsToComplete)
Whether to wait for the task to finish executing and close, true wait, false don't wait
void standby()
Pause all task jobs and restart with start() method
void pauseJob(JobKey jobKey)
Pause a Job through JobKey
void resumeJob(JobKey jobKey)
Wake up a suspended Job through JobKey
void pauseTrigger(TriggerKey triggerKey)
Suspend all jobs of a Trigger
void resumeTrigger(TriggerKey triggerKey)
Wake up a suspended Trigger's Job

3.JobBuilder

Method name Explain
JobBuilder newJob(Class <? extends Job> jobClass): Static method
Loading an instance of a Job
JobBuilder withIdentity(String name, String group)
Set up
Name and group of JobDetail
JobBuilder usingJobData(String dataKey, String value)
Pass parameters through key and value
JobBuilder usingJobData(JobDataMap newJobDataMap)
Pass parameters through JobDataMap
JobDetail build()
According to the previous parameter settings, build a JobDetail

 

4.JobDetail

Method name Explain
JobDataMap getJobDataMap()
Get the JobDataMap of the JobDetail
JobKey getKey()
Get the JobKey of the JobDetail

 

5.TriggerBuilder

Method name Explain
Trigger builder < trigger > newtrigger: static method
Load a Trigger
TriggerBuilder<T> withIdentity(String name, String group)
Set up
Trigger name and group
TriggerBuilder<T> usingJobData(String dataKey, String value)
Pass parameters through key and value
TriggerBuilder<T> usingJobData(JobDataMap newJobDataMap)
Pass parameters through JobDataMap
TriggerBuilder<SBT> withSchedule(ScheduleBuilder<SBT> schedBuilder)
Associate a ScheduleBuilder, usually SimpleScheduleBuilder or CronScheduleBuilder
T build()
According to the previous parameter settings, build a Trigger

6.Trigger

Method name Explain
JobDataMap getJobDataMap()
Get the JobDataMap of the JobDetail
 Date getNextFireTime()
Get next execution time
TriggerKey getKey()
Get the Trigger key of the Trigger
Date getEndTime()
Get end time
Date getStartTime()
Get start time

7.SimpleScheduleBuilder

Method name Explain
SimpleScheduleBuilder repeatSecondlyForever(int seconds): static method

 

Build a repeat, in seconds
SimpleScheduleBuilder repeatSecondlyForTotalCount(int count, int seconds): static method
Repeat, interval in seconds, and execute a certain number of times.
Similar to the above two repeated static methods, there are also by minute and by hour. Because too much content is not written out, the method names are similar.
 
SimpleScheduleBuilder withRepeatCount(int triggerRepeatCount)
Number of repetitions, note: if it is 1, it will be executed twice, because the run will execute once immediately, and so on.

8.CronScheduleBuilder

Method name Explain
CronScheduleBuilder cronSchedule(String cronExpression): static method

 

Building a CronScheduleBuilder based on cron expression

 

9.CronExpression

Method name Explain
boolean isValidExpression(String cronExpression): static method

 

Verify Cron expression
CronExpression(String cronExpression)
Constructor to check a Cron expression. If it fails, an exception will be thrown. The exception information contains the reason for failure

 

8, Cron expression

Cron expression is used to configure CronTrigger instance. Cron expression is a string composed of 7 subexpressions (the 7th one can be omitted). The general format is as follows: * * * *? Or * * * *? *, each subexpression represents a date detail, as follows:

position Explain Allowable value Special characters allowed
1 Seconds seconds 0-59 , / * -
2 Minutes 0-59 , / * -
3 Hours hours 0-23 , / * -
4 Day of month 1-31 , / * - ? L W C
5 Month months 1-12 or JAN-DEC in English , / * -
6 Day of week 1-7 or SUN-SAT in English , / * - ? L C #
7 Year (optional field) 1970-2099 (generally not written) , / * -

Meaning of special characters:

character Meaning
, (comma) Represents multiple values. If comma is used to separate 5, 10, 20 in seconds, it means execution in 5, 10, 20 seconds. It is understood as or.
? Indicates that no value is specified for the fourth (day of the month) and sixth (day of the week), because the fourth and sixth are conflicting. If the fourth has a value, the sixth must be?, and vice versa.
* Indicates all possible values. If * is used in seconds, it means every second of 60 seconds is executed. If * is used in hours, it means every hour of 24 hours is executed.
- Indicates the interval. If 6-8 is used for hours, then 6, 7 and 8 points will be executed.
/ Represents the interval. If 0 / 20 is used in seconds, it means every 20 seconds.
# Indicates the day of the third week of the month, such as 6 × 3, which indicates the Friday of the third week of the month (foreign Sunday = our Monday)
W Specify the working day closest to the given date (Monday to Friday)
L The fourth digit (day of the month) indicates the last day of the month, the sixth digit (day of the week) indicates the last week X of the month, and the sixth digit 6L indicates the last Friday of the month

9, Trigger trigger

Trigger triggers are mainly divided into two categories: Simple trigger (associated with SimpleScheduleBuilder) and Cron trigger (associated with CronScheduleBuilder). The use of SimpleScheduleBuilder and API settings are described in the above case. See the use of CronScheduleBuilder below.

1. Test code:

public class QuartzTest {


    public static void main(String[] args) throws SchedulerException{
        //1. Scheduler
        SchedulerFactory schedulerfactory = new StdSchedulerFactory();
        //Get the scheduler, the scheduler only needs one, can schedule multiple tasks
        Scheduler scheduler = schedulerfactory.getScheduler();
        //2.Job instance (JobDetil)
        JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
                .withIdentity("job", "default") //Name: task name, group: group name
                .build();
        //3. Trigger
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger", "default") //Name: trigger name, group: group name
                .startNow() //Do it now
                .withSchedule(CronScheduleBuilder.cronSchedule("0/3 * * * * ?"))//Using Cron triggers
                .build();
        //4. Associate Job with trigger
        scheduler.scheduleJob(jobDetail,trigger);
        scheduler.start();
        //Let the main thread block, easy to test
        Thread.yield();
    }


    public static class MyJob implements Job {

        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            //Print current time
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = dateFormat.format(new Date());
            System.out.println(date);
        }
    }
}

2. Implementation results:

The cron expression is: 0 / 3 * * *? That is, it starts from 0 seconds and executes every 3 seconds.

 

10, Configuration of StdSchedulerFactory

The API of StdSchedulerFactory is described above. There is an initialize(Properties props) method to initialize StdSchedulerFactory. The commonly used configuration property names and values are as follows:

Attribute name Explain
org.quartz.threadPool.class Which thread pool to use (to implement the thread pool of org.quartz.spi.ThreadPool interface), generally org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount  The number of threads in the thread pool should not exceed 100, depending on your situation
org.quartz.threadPool.threadPriority  Thread priority, 1-10. The smaller the number, the higher the priority. Generally, use 5.
org.quartz.scheduler.instanceName
Name of scheduler
org.quartz.scheduler.instanceId
Create a Key value for the scheduler. The Key must be unique among all the schedulers. Generally, fill in AUTO to make quartz generate automatically.
org.quartz.jobStore.class
Task scheduling storage (an instance of org.quartz.spi.JobStore interface needs to be implemented), usually org.quartz.impl.jdbc jobstore.jobstoretx

 

11, Tools

The basic contents of quartz are outlined above, and the next blog will give a high-level content overview. Before that, a quartz task scheduling tool class written by myself is presented, which can easily schedule any method of any class according to interval or corn expression. The code is as follows:

public class SchedulerUtils {

    private static StdSchedulerFactory schedulerfactory = new StdSchedulerFactory();



    public static final int SECONDS = 1;

    public static final int MINUTES = 2;

    public static final int HOURS = 3;


    private static String CLASS_KEY = "CLASS-KEY";
    private static String METHOD_KEY = "METHOD-KEY";
    private static String PARAMS_KEY = "PARAMS-KEY";

    /**
     * Initialize StdSchedulerFactory
     * @param map Initialization parameters
     * @throws SchedulerException
     */
    public static void init(Map<String,String> map) throws SchedulerException {
        Properties properties = new Properties();
        for(Map.Entry<String, String> entry : map.entrySet()) {
            properties.setProperty(entry.getKey(),entry.getValue());
        }
        init(properties);
    }

    public static void init(Properties properties) throws SchedulerException {
        schedulerfactory.initialize(properties);
    }

    /**
     *  Timed execution by Cron expression
     * @param clazzName Full class name
     * @param methodName Method name
     * @param args Method parameter
     * @param cron cron Expression
     * @throws Exception
     */
    public static void executeJobCron(String clazzName, String methodName, List<Object> args,String cron) throws Exception {
        executeJobCron(clazzName,methodName,args,cron,null,null);
    }

    /**
     *  Timed execution by Cron expression
     * @param clazzName Full class name
     * @param methodName Method name
     * @param args Method parameter
     * @param cron cron Expression
     * @param startDate Start time, if you start to fill in null or new Date() immediately
     * @param endDate End time. If there is no end time, fill in null
     * @throws Exception
     */
    public static void executeJobCron(String clazzName, String methodName, List<Object> args,String cron,Date startDate,Date endDate) throws Exception {
        JobDetail jobDetail = jobDetailHandle(clazzName, methodName, args);
        Trigger trigger = cronTriggerTimeHandle(cron,startDate,endDate);
        Scheduler scheduler = getScheduler();
        scheduler.scheduleJob(jobDetail,trigger);
        scheduler.start();
    }


    public static void executeJob(String clazzName, String methodName, List<Object> args, int timeUnit, int interval, Date endDate) throws Exception{
        executeJob(clazzName,methodName,args,timeUnit,interval,-1,null,endDate);
    }


    public static void executeJob(String clazzName, String methodName, List<Object> args, int timeUnit, int interval)  throws Exception{
        executeJob(clazzName,methodName,args,timeUnit,interval,-1,null,null);
    }

    public static void executeJob(String clazzName, String methodName, List<Object> args, int timeUnit, int interval, int count)  throws Exception{
        executeJob(clazzName,methodName,args,timeUnit,interval,count,null,null);
    }


    /**
     *  Execute regularly according to interval time
     * @param clazzName Full class name
     * @param methodName Method name
     * @param args Method parameter
     * @param timeUnit Time unit, refer to this type of attribute definition
     * @param interval Interval length
     * @param count Total number of executions, if both execution total and end time exist, then by end time.
     * @param startDate Start time, if you start to fill in null or new Date() immediately
     * @param endDate End time. If there is no end time, fill in null
     * @throws Exception
     */
    public static void executeJob(String clazzName, String methodName, List<Object> args, int timeUnit, int interval, int count,Date startDate,Date endDate)  throws Exception {
        JobDetail jobDetail = jobDetailHandle(clazzName, methodName, args);
        Trigger trigger = simpleTriggerTimeHandle(timeUnit,interval, count,startDate,endDate);
        Scheduler scheduler = getScheduler();
        scheduler.scheduleJob(jobDetail,trigger);
        scheduler.start();
    }

    private static JobDetail jobDetailHandle(String clazzName, String methodName, List<Object> args) throws NoSuchMethodException, ClassNotFoundException {
        JobDataMap jobDataMap = new JobDataMap();
        Class clazz = Class.forName(clazzName);
        Method method = findMethod(clazz,methodName,args);
        jobDataMap.put(CLASS_KEY,clazz);
        jobDataMap.put(METHOD_KEY,method);
        jobDataMap.put(PARAMS_KEY,args);
        JobDetail jobDetail = JobBuilder.newJob(TaskJob.class)
                .withIdentity("job")
                .usingJobData(jobDataMap)
                .build();
        return jobDetail;
    }

    private static Trigger simpleTriggerTimeHandle(int timeUnit, int interval, int count, Date startDate,Date emdDate) {
        TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger()
                .withIdentity("simpleTrigger");
        if(startDate == null) {
            startDate = new Date();
        }
        triggerBuilder.startAt(startDate);
        triggerBuilder.endAt(emdDate);
        if(count > 0) {
            switch (timeUnit) {
                case SECONDS : triggerBuilder.withSchedule(SimpleScheduleBuilder.repeatSecondlyForTotalCount(count,interval));
                    break;
                case MINUTES : triggerBuilder.withSchedule(SimpleScheduleBuilder.repeatMinutelyForTotalCount(count,interval));
                    break;
                case HOURS : triggerBuilder.withSchedule(SimpleScheduleBuilder.repeatHourlyForTotalCount(count,interval));
                    break;
            }
        }
        return triggerBuilder.build();
    }

    private static Trigger cronTriggerTimeHandle(String cron,Date startDate,Date emdDate) throws ParseException {
        new CronExpression(cron);
        if(startDate == null) {
            startDate = new Date();
        }
        Trigger trigger =  TriggerBuilder.newTrigger()
                .withIdentity("cronTrigger")
                .startAt(startDate)
                .endAt(emdDate)
                .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                .build();
        return trigger;
    }

    private static Scheduler getScheduler() throws SchedulerException {
        return schedulerfactory.getScheduler();
    }

    private static Method findMethod(Class clazz,String methodName,List<Object> args) throws NoSuchMethodException {
        Method method;
        if(args != null && !args.isEmpty()) {
            Class<?>[] paramsTypes = getMethodParamsType(args);
            method = clazz.getDeclaredMethod(methodName,paramsTypes);
        }else {
            method = clazz.getDeclaredMethod(methodName);
        }
        return method;
    }


    private static Class<?>[] getMethodParamsType(List<Object> methodParams) {
        Class<?>[] classs = new Class<?>[methodParams.size()];
        int index = 0;
        for (Object os : methodParams)
        {
            classs[index] = os.getClass();
            index++;
        }
        return classs;
    }

    public static class TaskJob implements Job {

        private Map<Class,Object> objectMap = new ConcurrentHashMap<Class, Object>();

        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            JobDataMap dataMap = jobExecutionContext.getMergedJobDataMap();
            Class clazz = (Class) dataMap.get(CLASS_KEY);
            Object object;
            try {
                object = getObject(clazz);
                Method method = (Method) dataMap.get(METHOD_KEY);
                Parameter[] parameters = method.getParameters();
                if (parameters.length > 0) {
                    List<Object> args = (List<Object>) dataMap.get(PARAMS_KEY);
                    Object[] objects = args.toArray();
                    method.invoke(object, objects);
                }else {
                    method.invoke(object);
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }

        private Object getObject(Class clazz) throws IllegalAccessException, InstantiationException {
            Object object = objectMap.get(clazz);
            if(object == null) {
                object = clazz.newInstance();
                objectMap.put(clazz,object);
            }
            return object;
        }
    }
}

        

66 original articles published, 82 praised, 100000 visitors+
Private letter follow

Posted by php2MySQL on Wed, 11 Mar 2020 23:47:17 -0700