package org.jetlinks.community.standalone.extend.job;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;

public class QuartzSchedulerWithReflection {

    public static void main(String[] args) throws SchedulerException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, InterruptedException {
        // Grab the Scheduler instance from the Factory
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

        // and start it off
        scheduler.start();

        // List of JobInfo objects containing job class names and interval times
        List<JobInfo> jobInfos = Arrays.asList(
                new JobInfo("org.jetlinks.community.standalone.extend.modbusrtu.test.HelloJob", 10,true),
                new JobInfo( "org.jetlinks.community.standalone.extend.modbusrtu.test.Hello2Job", 20,true)
        );

        for (JobInfo jobInfo : jobInfos) {
            try {
                // Use reflection to get the Class object
                Class<?> jobClass = Class.forName(jobInfo.getJobClassName());

                // Create an instance of the job using the default constructor (if needed, use a factory method or DI)
                // Note: We're not actually creating an instance here because Quartz will do it for us.
                // We just need the Class object to pass to newJob().

                // Define the job and tie it to the specified class
                JobDetail job = newJob((Class<? extends Job>) jobClass)
                        .withIdentity(jobInfo.getJobClassName().toLowerCase() + "Job", "group1")
                        .build();

                // Trigger the job to run now, and then repeat every 'intervalInSeconds' seconds
                Trigger trigger = newTrigger()
                        .withIdentity(jobInfo.getJobClassName().toLowerCase() + "Trigger", "group1")
                        .startNow()
                        .withSchedule(simpleSchedule()
                                .withIntervalInSeconds(jobInfo.getIntervalInSeconds())
                                .repeatForever())
                        .build();

                System.out.println(jobInfo.getJobClassName().toLowerCase() + "Job"+ Thread.currentThread().getName());

                // Tell Quartz to schedule the job using our trigger
                // Only schedule the job if shouldStart is true
                if (jobInfo.isShouldStart()) {
                    scheduler.scheduleJob(job, trigger);
                } else {
                    // Optionally, you could store the job and trigger somewhere
                    // to be able to start them later using scheduler.scheduleJob()
                    System.out.println("Job " + jobInfo.getJobClassName() + " will not be started initially.");
                }
            }catch (Exception e){
               e.printStackTrace();
            }

        }

        // Let the scheduler run for some time (e.g., 60 seconds to see both jobs run at least once)
        Thread.sleep(60000);

        // Shutdown the scheduler
        scheduler.shutdown();
    }
}
package org.jetlinks.community.standalone.extend.job;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

public class QuartzSchedulerUtils {

    // 获取Scheduler实例
    private static Scheduler getScheduler() throws SchedulerException {
        return StdSchedulerFactory.getDefaultScheduler();
    }

    // 启动Scheduler(如果尚未启动)
    public static void startScheduler() throws SchedulerException {
        Scheduler scheduler = getScheduler();
        if (!scheduler.isStarted()) {
            scheduler.start();
            System.out.println("Scheduler started.");
        } else {
            System.out.println("Scheduler is already started.");
        }
    }

    // 停止Scheduler(等待所有任务完成或立即停止)
    public static void stopScheduler(boolean waitForJobsToComplete) throws SchedulerException {
        Scheduler scheduler = getScheduler();
        if (scheduler.isStarted()) {
            scheduler.shutdown(waitForJobsToComplete);
            System.out.println("Scheduler stopped. WaitForJobsToComplete: " + waitForJobsToComplete);
        } else {
            System.out.println("Scheduler is already stopped.");
        }
    }

    // 暂停指定任务
    public static void pauseJob(String jobName, String jobGroupName) throws SchedulerException {
        Scheduler scheduler = getScheduler();
        JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
        if (scheduler.checkExists(jobKey)) {
            scheduler.pauseJob(jobKey);
            System.out.println("Job paused: " + jobName + " in group: " + jobGroupName);
        } else {
            System.out.println("Job does not exist: " + jobName + " in group: " + jobGroupName);
        }
    }

    // 恢复指定任务
    public static void resumeJob(String jobName, String jobGroupName) throws SchedulerException {
        Scheduler scheduler = getScheduler();
        JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
        if (scheduler.checkExists(jobKey)) {
            scheduler.resumeJob(jobKey);
            System.out.println("Job resumed: " + jobName + " in group: " + jobGroupName);
        } else {
            System.out.println("Job does not exist: " + jobName + " in group: " + jobGroupName);
        }
    }

    // 删除指定任务(先停止触发器,再删除任务)
    public static void deleteJob(String jobName, String jobGroupName) throws SchedulerException {
        Scheduler scheduler = getScheduler();
        JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroupName);
        if (scheduler.checkExists(jobKey)) {
            if (scheduler.checkExists(triggerKey)) {
                scheduler.pauseTrigger(triggerKey); // 停止触发器(可选,但推荐)
                scheduler.unscheduleJob(triggerKey); // 移除触发器
            }
            scheduler.deleteJob(jobKey);
            System.out.println("Job deleted: " + jobName + " in group: " + jobGroupName);
        } else {
            System.out.println("Job does not exist: " + jobName + " in group: " + jobGroupName);
        }
    }

    // 示例Job类
    public static class HelloJob implements Job {
        @Override
        public void execute(JobExecutionContext context) throws JobExecutionException {
            System.out.println("Hello, Quartz! " + new java.util.Date());
        }
    }

    // 示例:如何使用这些工具方法
    public static void main(String[] args) throws SchedulerException {
        // 启动Scheduler
        startScheduler();

        // 创建并调度一个示例Job(此步骤通常在实际应用中会复杂得多)
        JobDetail job = JobBuilder.newJob(HelloJob.class)
                .withIdentity("helloJob", "group1")
                .build();
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("helloTrigger", "group1")
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(10)
                        .repeatForever())
                .build();
        getScheduler().scheduleJob(job, trigger);

        // 暂停任务
        pauseJob("helloJob", "group1");

        // 恢复任务(可选,根据需要)
        // resumeJob("helloJob", "group1");

        // 停止Scheduler(等待所有任务完成,或者设置为false以立即停止)
        // stopScheduler(true); // 或者 stopScheduler(false);
    }
}
package org.jetlinks.community.standalone.extend.job;

class JobInfo {
    String jobClassName;
    int intervalInSeconds;

    boolean shouldStart; // 控制作业是否应该开始的字段

    // Constructor, getters, and setters omitted for brevity

    public JobInfo(String jobClassName, int intervalInSeconds, boolean shouldStart) {
        this.jobClassName = jobClassName;
        this.intervalInSeconds = intervalInSeconds;
        this.shouldStart = shouldStart;
    }

    public String getJobClassName() {
        return jobClassName;
    }

    public void setJobClassName(String jobClassName) {
        this.jobClassName = jobClassName;
    }

    public int getIntervalInSeconds() {
        return intervalInSeconds;
    }

    public void setIntervalInSeconds(int intervalInSeconds) {
        this.intervalInSeconds = intervalInSeconds;
    }

    public boolean isShouldStart() {
        return shouldStart;
    }

    public void setShouldStart(boolean shouldStart) {
        this.shouldStart = shouldStart;
    }
}

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐