org.quartz.SchedulerFactory - java examples

Here are the examples of the java api org.quartz.SchedulerFactory taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

93 Examples 7

19 View Complete Implementation : CronSchedulerHelper.java
Copyright Apache License 2.0
Author : kingston-csj
/**
 * 初始化
 * @param path 配置文件的路径
 * @throws SchedulerException
 */
public static synchronized void init(String path) throws SchedulerException {
    Objects.requireNonNull(path);
    SchedulerFactory schedulerFactory = new StdSchedulerFactory(path);
    scheduler = schedulerFactory.getScheduler();
}

19 View Complete Implementation : QuartzPlugin.java
Copyright Apache License 2.0
Author : OpeningO
public clreplaced QuartzPlugin implements IPlugin {

    public static final String VERSION_1 = "1";

    private static final String JOB = "job";

    private final Log logger = Log.getLog(getClreplaced());

    private Map<Job, String> jobs = Maps.newLinkedHashMap();

    private String version;

    private SchedulerFactory sf;

    private Scheduler scheduler;

    private String jobConfig;

    private String confConfig;

    private Map<String, String> jobProp;

    public QuartzPlugin(String jobConfig, String confConfig) {
        this.jobConfig = jobConfig;
        this.confConfig = confConfig;
    }

    public QuartzPlugin(String jobConfig) {
        this.jobConfig = jobConfig;
    }

    public QuartzPlugin() {
    }

    public QuartzPlugin add(String jobCronExp, Job job) {
        jobs.put(job, jobCronExp);
        return this;
    }

    @Override
    public boolean start() {
        loadJobsFromProperties();
        startJobs();
        return true;
    }

    private void startJobs() {
        try {
            if (StrKit.notBlank(confConfig)) {
                sf = new StdSchedulerFactory(confConfig);
            } else {
                sf = new StdSchedulerFactory();
            }
            scheduler = sf.getScheduler();
        } catch (SchedulerException e) {
            Throwables.propagate(e);
        }
        Set<Map.Entry<Job, String>> set = jobs.entrySet();
        for (Map.Entry<Job, String> entry : set) {
            Job job = entry.getKey();
            String jobClreplacedName = job.getClreplaced().getName();
            String jobCronExp = entry.getValue();
            JobDetail jobDetail;
            CronTrigger trigger;
            // JobDetail and CornTrigger are clreplacedes in 1.x version,but are interfaces in 2.X version.
            if (VERSION_1.equals(version)) {
                jobDetail = Reflect.on("org.quartz.JobDetail").create(jobClreplacedName, jobClreplacedName, job.getClreplaced()).get();
                trigger = Reflect.on("org.quartz.CronTrigger").create(jobClreplacedName, jobClreplacedName, jobCronExp).get();
            } else {
                jobDetail = Reflect.on("org.quartz.JobBuilder").call("newJob", job.getClreplaced()).call("withIdenreplacedy", jobClreplacedName, jobClreplacedName).call("build").get();
                Object temp = Reflect.on("org.quartz.TriggerBuilder").call("newTrigger").get();
                temp = Reflect.on(temp).call("withIdenreplacedy", jobClreplacedName, jobClreplacedName).get();
                temp = Reflect.on(temp).call("withSchedule", Reflect.on("org.quartz.CronScheduleBuilder").call("cronSchedule", jobCronExp).get()).get();
                trigger = Reflect.on(temp).call("build").get();
            }
            Date ft = Reflect.on(scheduler).call("scheduleJob", jobDetail, trigger).get();
            logger.debug(Reflect.on(jobDetail).call("getKey") + " has been scheduled to run at: " + ft + " " + "and repeat based on expression: " + Reflect.on(trigger).call("getCronExpression"));
        }
        try {
            scheduler.start();
        } catch (SchedulerException e) {
            Throwables.propagate(e);
        }
    }

    private void loadJobsFromProperties() {
        if (StrKit.isBlank(jobConfig)) {
            return;
        }
        jobProp = ResourceKit.readProperties(jobConfig);
        Set<Map.Entry<String, String>> entries = jobProp.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            String key = entry.getKey();
            if (!key.endsWith(JOB) || !isEnableJob(enable(key))) {
                continue;
            }
            String jobClreplacedName = jobProp.get(key) + "";
            String jobCronExp = jobProp.get(cronKey(key)) + "";
            Clreplaced<Job> job = Reflect.on(jobClreplacedName).get();
            try {
                jobs.put(job.newInstance(), jobCronExp);
            } catch (Exception e) {
                Throwables.propagate(e);
            }
        }
    }

    private String enable(String key) {
        return key.substring(0, key.lastIndexOf(JOB)) + "enable";
    }

    private String cronKey(String key) {
        return key.substring(0, key.lastIndexOf(JOB)) + "cron";
    }

    public QuartzPlugin version(String version) {
        this.version = version;
        return this;
    }

    private boolean isEnableJob(String enableKey) {
        Object enable = jobProp.get(enableKey);
        if (enable != null && "false".equalsIgnoreCase((enable + "").trim())) {
            return false;
        }
        return true;
    }

    @Override
    public boolean stop() {
        try {
            scheduler.shutdown();
        } catch (SchedulerException e) {
            Throwables.propagate(e);
        }
        return true;
    }

    public QuartzPlugin confConfig(String confConfig) {
        this.confConfig = confConfig;
        return this;
    }

    public QuartzPlugin jobConfig(String jobConfig) {
        this.jobConfig = jobConfig;
        return this;
    }
}

19 View Complete Implementation : JobSchedulerService.java
Copyright BSD 3-Clause "New" or "Revised" License
Author : lutece-platform
/**
 * Initialize the service.
 */
private void init() {
    SchedulerFactory factory = new StdSchedulerFactory();
    try {
        _scheduler = factory.getScheduler();
        _scheduler.start();
        AppLogService.info("Lutece job scheduler started.");
    } catch (SchedulerException e) {
        AppLogService.error("Error starting the Lutece job scheduler ", e);
    }
}

19 View Complete Implementation : SchedulerFactoryBean.java
Copyright MIT License
Author : codeEngraver
/**
 * Create a SchedulerFactory if necessary and apply locally defined Quartz properties to it.
 * @return the initialized SchedulerFactory
 */
private SchedulerFactory prepareSchedulerFactory() throws SchedulerException, IOException {
    SchedulerFactory schedulerFactory = this.schedulerFactory;
    if (schedulerFactory == null) {
        // Create local SchedulerFactory instance (typically a StdSchedulerFactory)
        schedulerFactory = BeanUtils.instantiateClreplaced(this.schedulerFactoryClreplaced);
        if (schedulerFactory instanceof StdSchedulerFactory) {
            initSchedulerFactory((StdSchedulerFactory) schedulerFactory);
        } else if (this.configLocation != null || this.quartzProperties != null || this.taskExecutor != null || this.dataSource != null) {
            throw new IllegalArgumentException("StdSchedulerFactory required for applying Quartz properties: " + schedulerFactory);
        }
    // Otherwise, no local settings to be applied via StdSchedulerFactory.initialize(Properties)
    }
    // Otherwise, replacedume that externally provided factory has been initialized with appropriate settings
    return schedulerFactory;
}

19 View Complete Implementation : QuartzManagerUtils.java
Copyright Apache License 2.0
Author : smartloli
/**
 * Used to schedule and send different types of alarm queue information. Such as
 * email, dingding, wechat etc.
 *
 * @author smartloli.
 *
 *         Created by Oct 24, 2019
 */
public clreplaced QuartzManagerUtils {

    public static final String KE_JOB_GROUP_NAME = "KE_JOB_GROUP_NAME";

    private static SchedulerFactory schedulerFactory = new StdSchedulerFactory();

    /**
     * Add new job.
     */
    public static void addJob(BaseJobContext jobContext, String jobName, Clreplaced<? extends Job> jobClreplaced, String cron) {
        try {
            Scheduler sched = schedulerFactory.getScheduler();
            JobDetail jobDetail = JobBuilder.newJob(jobClreplaced).withIdenreplacedy(jobName, KE_JOB_GROUP_NAME).build();
            jobDetail.getJobDataMap().put(AlarmQueue.JOB_PARAMS, jobContext);
            TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
            triggerBuilder.withIdenreplacedy("ke_trigger_name_" + new Date().getTime(), "ke_trigger_group_" + new Date().getTime());
            triggerBuilder.startNow();
            triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
            CronTrigger trigger = (CronTrigger) triggerBuilder.build();
            sched.scheduleJob(jobDetail, trigger);
            if (!sched.isShutdown()) {
                sched.start();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Modify job.
     */
    public static void modifyJobTime(String jobName, String cron) {
        try {
            Scheduler sched = schedulerFactory.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey("ke_trigger_name_" + new Date().getTime(), "ke_trigger_group_" + new Date().getTime());
            CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerKey);
            if (trigger == null) {
                return;
            }
            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(cron)) {
                TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
                triggerBuilder.withIdenreplacedy("ke_trigger_name_" + new Date().getTime(), "ke_trigger_group_" + new Date().getTime());
                triggerBuilder.startNow();
                triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
                trigger = (CronTrigger) triggerBuilder.build();
                sched.rescheduleJob(triggerKey, trigger);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Remove job.
     */
    public static void removeJob(String jobName) {
        try {
            Scheduler sched = schedulerFactory.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey("ke_trigger_name_" + new Date().getTime(), "ke_trigger_group_" + new Date().getTime());
            sched.pauseTrigger(triggerKey);
            sched.unscheduleJob(triggerKey);
            sched.deleteJob(JobKey.jobKey(jobName, KE_JOB_GROUP_NAME));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Start all jobs.
     */
    public static void startJobs() {
        try {
            Scheduler sched = schedulerFactory.getScheduler();
            sched.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Shutdown all jobs.
     */
    public static void shutdownJobs() {
        try {
            Scheduler sched = schedulerFactory.getScheduler();
            if (!sched.isShutdown()) {
                sched.shutdown();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Get quartz cron date. {@code delayMill} unit second, such 1 sec.
     */
    public static String getCron(final Date date, int delaySecond) {
        SimpleDateFormat sdf = new SimpleDateFormat("ss mm HH dd MM ? yyyy");
        String formatTimeStr = "";
        if (date != null) {
            try {
                formatTimeStr = sdf.format(sdf.parse(sdf.format(date.getTime() + delaySecond * 1000)));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return formatTimeStr;
    }
}

19 View Complete Implementation : CronSchedulerHelper.java
Copyright Apache License 2.0
Author : kingston-csj
public static synchronized void initAndStart() throws SchedulerException {
    SchedulerFactory schedulerFactory;
    schedulerFactory = new StdSchedulerFactory(CONFIG_PATH);
    scheduler = schedulerFactory.getScheduler();
    scheduler.start();
}

19 View Complete Implementation : QuartzManager.java
Copyright Apache License 2.0
Author : fengzhizi715
/**
 * Created by tony on 2019-05-11.
 */
public clreplaced QuartzManager {

    private static SchedulerFactory schedulerFactory = new StdSchedulerFactory();

    /**
     * 添加一个定时任务
     *
     * @param jobName 任务名
     * @param jobGroupName  任务组名
     * @param triggerName 触发器名
     * @param triggerGroupName 触发器组名
     * @param jobClreplaced  任务
     * @param cron   时间设置,参考quartz说明文档
     */
    public static void addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName, Clreplaced jobClreplaced, String cron) {
        try {
            Scheduler sched = schedulerFactory.getScheduler();
            // 任务名,任务组,任务执行类
            JobDetail jobDetail = JobBuilder.newJob(jobClreplaced).withIdenreplacedy(jobName, jobGroupName).build();
            // 触发器
            TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
            // 触发器名,触发器组
            triggerBuilder.withIdenreplacedy(triggerName, triggerGroupName);
            triggerBuilder.startNow();
            // 触发器时间设定
            triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
            // 创建Trigger对象
            CronTrigger trigger = (CronTrigger) triggerBuilder.build();
            // 调度容器设置JobDetail和Trigger
            sched.scheduleJob(jobDetail, trigger);
            // 启动
            if (!sched.isShutdown()) {
                sched.start();
            }
        } catch (Exception e) {
            throw new SpiderException(e);
        }
    }

    /**
     * 添加一个定时任务
     *
     * @param jobBean
     * @param jobClreplaced
     * @param cron
     * @param spider
     * @param requests
     */
    public static void addJob(SpiderJobBean jobBean, Clreplaced<SpiderJob> jobClreplaced, String cron, Spider spider, Request... requests) {
        try {
            Scheduler sched = schedulerFactory.getScheduler();
            // 任务名,任务组,任务执行类
            JobDetail jobDetail = JobBuilder.newJob(jobClreplaced).withIdenreplacedy(jobBean.getJobName(), jobBean.getJobGroupName()).build();
            jobDetail.getJobDataMap().put("spider", spider);
            jobDetail.getJobDataMap().put("requests", requests);
            // 触发器
            TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
            // 触发器名,触发器组
            triggerBuilder.withIdenreplacedy(jobBean.getTriggerName(), jobBean.getTriggerGroupName());
            triggerBuilder.startNow();
            // 触发器时间设定
            triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
            // 创建Trigger对象
            CronTrigger trigger = (CronTrigger) triggerBuilder.build();
            // 调度容器设置JobDetail和Trigger
            sched.scheduleJob(jobDetail, trigger);
            // 启动
            if (!sched.isShutdown()) {
                sched.start();
            }
        } catch (Exception e) {
            throw new SpiderException(e);
        }
    }

    /**
     * 添加一个定时任务
     *
     * @param jobName 任务名
     * @param jobGroupName  任务组名
     * @param triggerName 触发器名
     * @param triggerGroupName 触发器组名
     * @param jobClreplaced  任务
     * @param cron   时间设置,参考quartz说明文档
     * @param proxyMap
     */
    public static void addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName, Clreplaced<ProxyPoolJob> jobClreplaced, String cron, Map<String, Clreplaced> proxyMap) {
        try {
            Scheduler sched = schedulerFactory.getScheduler();
            // 任务名,任务组,任务执行类
            JobDetail jobDetail = JobBuilder.newJob(jobClreplaced).withIdenreplacedy(jobName, jobGroupName).build();
            jobDetail.getJobDataMap().put("proxyMap", proxyMap);
            // 触发器
            TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
            // 触发器名,触发器组
            triggerBuilder.withIdenreplacedy(triggerName, triggerGroupName);
            triggerBuilder.startNow();
            // 触发器时间设定
            triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
            // 创建Trigger对象
            CronTrigger trigger = (CronTrigger) triggerBuilder.build();
            // 调度容器设置JobDetail和Trigger
            sched.scheduleJob(jobDetail, trigger);
            // 启动
            if (!sched.isShutdown()) {
                sched.start();
            }
        } catch (Exception e) {
            throw new SpiderException(e);
        }
    }

    /**
     * 修改一个任务的触发时间
     *
     * @param jobName
     * @param jobGroupName
     * @param triggerName 触发器名
     * @param triggerGroupName 触发器组名
     * @param cron   时间设置,参考quartz说明文档
     */
    public static void modifyJobTime(String jobName, String jobGroupName, String triggerName, String triggerGroupName, String cron) {
        try {
            Scheduler sched = schedulerFactory.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
            CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerKey);
            if (trigger == null) {
                return;
            }
            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(cron)) {
                /**
                 * 调用 rescheduleJob 开始
                 */
                // 触发器
                TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
                // 触发器名,触发器组
                triggerBuilder.withIdenreplacedy(triggerName, triggerGroupName);
                triggerBuilder.startNow();
                // 触发器时间设定
                triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
                // 创建Trigger对象
                trigger = (CronTrigger) triggerBuilder.build();
                sched.rescheduleJob(triggerKey, trigger);
            }
        } catch (Exception e) {
            throw new SpiderException(e);
        }
    }

    /**
     * 移除一个任务
     *
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param triggerGroupName
     */
    public static void removeJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName) {
        try {
            Scheduler sched = schedulerFactory.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
            // 停止触发器
            sched.pauseTrigger(triggerKey);
            // 移除触发器
            sched.unscheduleJob(triggerKey);
            // 删除任务
            sched.deleteJob(JobKey.jobKey(jobName, jobGroupName));
        } catch (Exception e) {
            throw new SpiderException(e);
        }
    }

    /**
     * 启动所有定时任务
     */
    public static void startJobs() {
        try {
            Scheduler sched = schedulerFactory.getScheduler();
            sched.start();
        } catch (Exception e) {
            throw new SpiderException(e);
        }
    }

    /**
     * 关闭所有定时任务
     */
    public static void shutdownJobs() {
        try {
            Scheduler sched = schedulerFactory.getScheduler();
            if (!sched.isShutdown()) {
                sched.shutdown();
            }
        } catch (Exception e) {
            throw new SpiderException(e);
        }
    }
}

19 View Complete Implementation : QuartzServer.java
Copyright Apache License 2.0
Author : AsuraTeam
/*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Interface.
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */
public void serve(SchedulerFactory schedFact, boolean console) throws Exception {
    sched = schedFact.getScheduler();
    sched.start();
    try {
        Thread.sleep(3000l);
    } catch (Exception ignore) {
    }
    System.out.println("\n*** The scheduler successfully started.");
    if (console) {
        System.out.println("\n");
        System.out.println("The scheduler will now run until you type \"exit\"");
        System.out.println("   If it was configured to export itself via RMI,");
        System.out.println("   then other process may now use it.");
        BufferedReader rdr = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            System.out.print("Type 'exit' to shutdown the server: ");
            if ("exit".equals(rdr.readLine())) {
                break;
            }
        }
        System.out.println("\n...Shutting down server...");
        sched.shutdown(true);
    }
}

19 View Complete Implementation : ScheduledInvocationManagerImpl.java
Copyright Educational Community License v2.0
Author : sakaiproject
public void setSchedulerFactory(SchedulerFactory schedulerFactory) {
    this.schedulerFactory = schedulerFactory;
}

19 View Complete Implementation : QuartzUtil.java
Copyright Apache License 2.0
Author : FoxBPM
/**
 * 创建定时任务工厂
 *
 * @return
 */
public final static SchedulerFactory createSchedulerFactory() {
    SchedulerFactory sf = new StdSchedulerFactory();
    return sf;
}

19 View Complete Implementation : CronSchedulerHelper.java
Copyright Apache License 2.0
Author : kingston-csj
/**
 * 初始化
 * @param path 配置文件的路径
 * @throws SchedulerException
 */
public static synchronized void initAndStart(String path) throws SchedulerException {
    Objects.requireNonNull(path);
    SchedulerFactory schedulerFactory;
    schedulerFactory = new StdSchedulerFactory(path);
    scheduler = schedulerFactory.getScheduler();
    scheduler.start();
}

19 View Complete Implementation : SchedulerMainService.java
Copyright BSD 2-Clause "Simplified" License
Author : iotoasis
/**
 * 스케줄러 서비스의 메인 클래스
 */
@Service
public clreplaced SchedulerMainService implements ApplicationContextAware {

    private static ApplicationContext context;

    private SchedulerFactory schedulerFactory = null;

    private Scheduler scheduler = null;

    private JobDetail jobDetail = null;

    private CronTrigger trigger = null;

    private SchDTO[] schDTO;

    private Log log = LogFactory.getLog(this.getClreplaced());

    /**
     * 스케줄러 초기화
     * @throws Exception
     * @return void
     */
    public void JobInit() throws Exception {
        try {
            if (scheduler != null && scheduler.isStarted())
                return;
            schedulerFactory = new StdSchedulerFactory();
            scheduler = schedulerFactory.getScheduler();
            scheduler.start();
            JobRegist();
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 스케줄러 인스턴스 얻기
     * @throws Exception
     * @return Scheduler
     */
    public Scheduler getScheduler() throws Exception {
        if (scheduler == null) {
            schedulerFactory = new StdSchedulerFactory();
            scheduler = schedulerFactory.getScheduler();
        }
        return scheduler;
    }

    /**
     * 스케줄러 Job등록
     * @throws Exception
     * @return void
     */
    public void JobRegist() throws Exception {
        Clreplaced<?> c = null;
        // 등록할 스케줄 정보 설정
        setSchList();
        for (int j = 0; j < schDTO.length; j++) {
            try {
                c = Clreplaced.forName(schDTO[j].getTask_clreplaced());
                jobDetail = new JobDetail(schDTO[j].getTask_id(), schDTO[j].getTask_group_id(), c);
                trigger = new CronTrigger(schDTO[j].getTask_id(), schDTO[j].getTask_group_id());
                trigger.setCronExpression(schDTO[j].getTask_expression());
                scheduler.scheduleJob(jobDetail, trigger);
            } catch (Exception e) {
                throw e;
            }
        }
    }

    /**
     * 스케줄러 목록
     * @throws Exception
     * @return void
     */
    public void statusSchList() throws Exception {
        setSchList();
        StringBuffer sb = new StringBuffer();
        for (int j = 0; j < schDTO.length; j++) {
            sb.append("trigger[");
            sb.append(j);
            sb.append("](group_id:");
            sb.append(schDTO[j].getTask_group_id());
            sb.append(",");
            sb.append(" task_id:");
            sb.append(schDTO[j].getTask_id());
            sb.append(") : ");
            sb.append(scheduler.getTriggerState(schDTO[j].getTask_id(), schDTO[j].getTask_group_id()));
            sb.append(" (not initiated:-1, running/standby:0, paused:1)");
            sb.append(Utils.NEW_LINE);
        }
        log.debug(sb.toString());
    }

    /**
     * 스케줄러 상태값 목록
     * @throws Exception
     * @return String
     */
    public String getStatusList() throws Exception {
        StringBuffer sb = new StringBuffer();
        setSchList();
        for (int j = 0; j < schDTO.length; j++) {
            sb.append("trigger[");
            sb.append(j);
            sb.append("](group_id:");
            sb.append(schDTO[j].getTask_group_id());
            sb.append(",");
            sb.append(" task_id:");
            sb.append(schDTO[j].getTask_id());
            sb.append(") : ");
            sb.append(scheduler.getTriggerState(schDTO[j].getTask_id(), schDTO[j].getTask_group_id()));
            sb.append(" (not initiated:-1, running/standby:0, paused:1)");
            if ((j + 1) != schDTO.length) {
                sb.append("<br>");
            }
        }
        return sb.toString();
    }

    /**
     * 스케줄 pause
     * @throws Exception
     * @return void
     */
    public void pauseSch() throws Exception {
        setSchList();
        for (int j = 0; j < schDTO.length; j++) {
            scheduler.pauseJob(schDTO[j].getTask_id(), schDTO[j].getTask_group_id());
            log.debug("[" + j + "] paused......");
        }
    }

    // resume
    public void resumeSch() throws Exception {
        setSchList();
        for (int j = 0; j < schDTO.length; j++) {
            scheduler.resumeJob(schDTO[j].getTask_id(), schDTO[j].getTask_group_id());
            log.debug("[" + j + "] resumed......");
        }
    }

    /**
     * 스케줄러 standby상태로 전환
     * @throws Exception
     * @return void
     */
    public void standbySch() throws Exception {
        setSchList();
        scheduler.standby();
        log.debug("scheduler is in state of standby ......");
    }

    /**
     * 스케줄러 시작
     * @throws Exception
     * @return void
     */
    public void startSch() throws Exception {
        setSchList();
        scheduler.start();
        log.debug("scheduler is in state of start ......");
    }

    /**
     * 스케줄러 멈춤
     * @throws Exception
     * @return void
     */
    public void shutdown() throws Exception {
        scheduler.shutdown();
    }

    /**
     * 스케줄 목록 설정
     * @throws Exception
     * @return void
     */
    private void setSchList() throws Exception {
        if (schDTO != null)
            return;
        // 스케줄정보 가져오기
        List<SchDTO> schList = new ArrayList<SchDTO>();
        try {
            SchService schService = getContext().getBean(SchService.clreplaced);
            schList = schService.selectList();
        } catch (SQLNonTransientConnectionException e) {
            System.gc();
        } catch (Exception e) {
            throw e;
        }
        schDTO = new SchDTO[schList.size()];
        for (int i = 0; i < schList.size(); i++) {
            schDTO[i] = schList.get(i);
            log.debug("schDTO[" + i + "] in SchedulerMainService================>" + schDTO[i].toString());
        }
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static ApplicationContext getContext() {
        return context;
    }
}

19 View Complete Implementation : AutoInvestScheduler.java
Copyright Apache License 2.0
Author : jeffpeiyt
public static void scheduleAutoInvest() {
    try {
        // Grab the Scheduler instance from the Factory
        SchedulerFactory sf = new StdSchedulerFactory();
        Scheduler sched = sf.getScheduler();
        String group = "group1";
        JobDetail job = newJob(InvestJob.clreplaced).withIdenreplacedy("investJob", group).build();
        CronTrigger trigger = newTrigger().withIdenreplacedy("investTrigger", group).withSchedule(CronScheduleBuilder.cronSchedule(Cfg.m.get(Cfg.T.CRON_EXPRESSION.name())).inTimeZone(TimeZone.getTimeZone("America/Los_Angeles"))).build();
        sched.scheduleJob(job, trigger);
        sched.start();
    // sched.shutdown(true);
    } catch (SchedulerException se) {
        logger.error("SchedulerException", se);
    } catch (Throwable e) {
        logger.error("Fails", e);
    }
}

19 View Complete Implementation : SchedulerServiceInit.java
Copyright Eclipse Public License 1.0
Author : eclipse
public static void initialize() throws KapuaException {
    logger.info("Starting scheduler service...");
    SchedulerFactory sf = new StdSchedulerFactory();
    try {
        sf.getScheduler().start();
    } catch (SchedulerException e) {
        throw KapuaException.internalError(e, "Cannot start scheduler service");
    }
    logger.info("Starting scheduler service... DONE");
}

19 View Complete Implementation : ScheduleServiceTest.java
Copyright Apache License 2.0
Author : fixteam
public void testGetSchedulerFactory() throws SchedulerException {
    SchedulerFactory schedulerFactory = scheduleService.getSchedulerFactory();
    Scheduler scheduler = schedulerFactory.getScheduler();
    // 获得到 scheduler 之后就能对定时任务框架进行操作 具体操作方式请参见 quartz 使用手册
    replacedertNotNull(scheduler);
}

19 View Complete Implementation : KSBSchedulerFactoryBean.java
Copyright Educational Community License v2.0
Author : kuali
@Override
protected Scheduler createScheduler(SchedulerFactory schedulerFactory, String schedulerName) throws SchedulerException {
    if (ConfigContext.getCurrentContextConfig().getObject(KSBConstants.Config.INJECTED_EXCEPTION_MESSAGE_SCHEDULER_KEY) != null) {
        try {
            schedulerInjected = true;
            Scheduler scheduler = (Scheduler) ConfigContext.getCurrentContextConfig().getObject(KSBConstants.Config.INJECTED_EXCEPTION_MESSAGE_SCHEDULER_KEY);
            scheduler.getListenerManager().addJobListener(new MessageServiceExecutorJobListener());
            return scheduler;
        } catch (Exception e) {
            throw new ConfigurationException(e);
        }
    }
    return super.createScheduler(schedulerFactory, schedulerName);
}

19 View Complete Implementation : SchedulerFactoryBean.java
Copyright GNU Affero General Public License v3.0
Author : kuali
/**
 * @see org.springframework.scheduling.quartz.SchedulerFactoryBean#createScheduler(org.quartz.SchedulerFactory, java.lang.String)
 */
@Override
protected Scheduler createScheduler(SchedulerFactory schedulerFactory, String schedulerName) throws SchedulerException {
    Scheduler scheduler = super.createScheduler(schedulerFactory, schedulerName);
    scheduler.addJobListener(new MessageServiceExecutorJobListener());
    return scheduler;
}

19 View Complete Implementation : CaptureScreen.java
Copyright Apache License 2.0
Author : apache
private Scheduler getScheduler() {
    if (_scheduler == null) {
        try {
            SchedulerFactory schdlrFactory = new StdSchedulerFactory(getQurtzProps("CaptureScreen"));
            _scheduler = schdlrFactory.getScheduler();
        } catch (SchedulerException e) {
            log.error("Unexpected error while creating scheduler", e);
        }
    }
    return _scheduler;
}

19 View Complete Implementation : SchedulerFactoryBean.java
Copyright MIT License
Author : codeEngraver
/**
 * Set an external Quartz {@link SchedulerFactory} instance to use.
 * <p>Default is an internal {@link StdSchedulerFactory} instance. If this method is
 * called, it overrides any clreplaced specified through {@link #setSchedulerFactoryClreplaced}
 * as well as any settings specified through {@link #setConfigLocation},
 * {@link #setQuartzProperties}, {@link #setTaskExecutor} or {@link #setDataSource}.
 * <p><b>NOTE:</b> With an externally provided {@code SchedulerFactory} instance,
 * local settings such as {@link #setConfigLocation} or {@link #setQuartzProperties}
 * will be ignored here in {@code SchedulerFactoryBean}, expecting the external
 * {@code SchedulerFactory} instance to get initialized on its own.
 * @since 4.3.15
 * @see #setSchedulerFactoryClreplaced
 */
public void setSchedulerFactory(SchedulerFactory schedulerFactory) {
    this.schedulerFactory = schedulerFactory;
}

19 View Complete Implementation : QuartzManager.java
Copyright Apache License 2.0
Author : quartzweb
/**
 * 设置 默认Scheduler工厂
 *
 * @param defualtSchedulerFactory 默认Scheduler工厂
 */
public void setDefualtSchedulerFactory(SchedulerFactory defualtSchedulerFactory) throws SchedulerException {
    this.defualtSchedulerFactory = defualtSchedulerFactory;
}

19 View Complete Implementation : SchedulerExecutor.java
Copyright Apache License 2.0
Author : AsuraTeam
/**
 * 获取Scheduler实例
 *
 * @author zhangshaobin
 * @created 2012-12-18 上午8:51:32
 *
 * @return Scheduler实例
 */
public static Scheduler getScheduler() {
    if (null == scheduler) {
        SchedulerFactory sf;
        try {
            sf = new StdSchedulerFactory("E:\\git-working\\asura-framework\\asura\\asura-dubbo\\src\\test\\java\\com\\asura\\test\\quartz.properties");
            scheduler = sf.getScheduler();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    return scheduler;
}

19 View Complete Implementation : ScheduledInvocationManagerImpl.java
Copyright Educational Community License v2.0
Author : sakaiproject
/**
 * componentId -> job key (name)
 * opaqueContent/contextId -> trigger key (name)
 *
 * jobs have groups and triggers have groups.
 * matching by quartz can be done on both of them and supports equals/startswith.
 * possiblity to have another table that does the opaqueID to UUID mapping?
 */
@Slf4j
public clreplaced ScheduledInvocationManagerImpl implements ScheduledInvocationManager {

    // The Quartz group name that contains all our Jobs and Triggers.
    public static final String GROUP_NAME = "org.sakaiproject.component.app.scheduler.jobs.ScheduledInvocationJob";

    /**
     * The key in the job data map that contains the opaque ID.
     */
    public static final String CONTEXT_ID = "contextId";

    /**
     * Dependency: IdManager
     */
    protected IdManager m_idManager = null;

    public void setIdManager(IdManager service) {
        m_idManager = service;
    }

    /**
     * Dependency: SchedulerFactory
     */
    protected SchedulerFactory schedulerFactory = null;

    public void setSchedulerFactory(SchedulerFactory schedulerFactory) {
        this.schedulerFactory = schedulerFactory;
    }

    private ContextMappingDAO dao;

    public void setDao(ContextMappingDAO dao) {
        this.dao = dao;
    }

    protected TriggerListener triggerListener;

    public void init() throws SchedulerException {
        log.info("init()");
        triggerListener = new ContextTriggerListener("ContextTriggerListener");
        ListenerManager listenerManager = schedulerFactory.getScheduler().getListenerManager();
        // Just filter on our group.
        listenerManager.addTriggerListener(triggerListener, GroupMatcher.triggerGroupEquals(GROUP_NAME));
    }

    public void destroy() throws SchedulerException {
        log.info("destroy()");
        ListenerManager listenerManager = schedulerFactory.getScheduler().getListenerManager();
        listenerManager.removeTriggerListener(triggerListener.getName());
    }

    @Override
    @Transactional(propagation = REQUIRES_NEW)
    public String createDelayedInvocation(Time time, String componentId, String opaqueContext) {
        Instant instant = Instant.ofEpochMilli(time.getTime());
        return createDelayedInvocation(instant, componentId, opaqueContext);
    }

    @Override
    @Transactional(propagation = REQUIRES_NEW)
    public String createDelayedInvocation(Instant instant, String componentId, String opaqueContext) {
        String uuid = m_idManager.createUuid();
        createDelayedInvocation(instant, componentId, opaqueContext, uuid);
        return uuid;
    }

    /**
     * Creates a new delated invocation. This exists so that the migration code can create a new delayed invocation
     * and specify the UUID that should be used.
     * @see org.sakaiproject.component.app.scheduler.jobs.SchedulerMigrationJob
     */
    @Transactional(propagation = REQUIRES_NEW)
    public void createDelayedInvocation(Instant instant, String componentId, String opaqueContext, String uuid) {
        String oldUuid = dao.get(componentId, opaqueContext);
        // Delete the existing one.
        if (oldUuid != null) {
            deleteDelayedInvocation(componentId, opaqueContext);
        }
        dao.add(uuid, componentId, opaqueContext);
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();
            JobKey key = new JobKey(componentId, GROUP_NAME);
            JobDetail detail = scheduler.getJobDetail(key);
            if (detail == null) {
                try {
                    detail = JobBuilder.newJob(ScheduledInvocationJob.clreplaced).withIdenreplacedy(key).storeDurably().build();
                    scheduler.addJob(detail, false);
                } catch (ObjectAlreadyExistsException se) {
                    // We can ignore this one as it means the job is already present. This should only happen
                    // due concurrent inserting of the job
                    log.debug("Failed to add job {} as it already exists ", key, se);
                }
            }
            // Non-repeating trigger.
            Trigger trigger = TriggerBuilder.newTrigger().withIdenreplacedy(uuid, GROUP_NAME).startAt(Date.from(instant)).forJob(key).usingJobData(CONTEXT_ID, opaqueContext).build();
            scheduler.scheduleJob(trigger);
            // This is so that we can do fast lookups.
            log.info("Created new Delayed Invocation: uuid=" + uuid);
        } catch (SchedulerException se) {
            dao.remove(uuid);
            log.error("Failed to create new Delayed Invocation: componentId=" + componentId + ", opaqueContext=" + opaqueContext, se);
        }
    }

    /* (non-Javadoc)
	 * @see org.sakaiproject.api.app.scheduler.ScheduledInvocationManager#deleteDelayedInvocation(java.lang.String)
	 */
    @Transactional(propagation = REQUIRES_NEW)
    public void deleteDelayedInvocation(String uuid) {
        log.debug("Removing Delayed Invocation: " + uuid);
        try {
            TriggerKey key = new TriggerKey(uuid, GROUP_NAME);
            schedulerFactory.getScheduler().unscheduleJob(key);
            dao.remove(uuid);
        } catch (SchedulerException e) {
            log.error("Failed to remove Delayed Invocation: uuid=" + uuid, e);
        }
    }

    /* (non-Javadoc)
	 * @see org.sakaiproject.api.app.scheduler.ScheduledInvocationManager#deleteDelayedInvocation(java.lang.String, java.lang.String)
	 */
    @Transactional(propagation = REQUIRES_NEW)
    public void deleteDelayedInvocation(String componentId, String opaqueContext) {
        log.debug("componentId=" + componentId + ", opaqueContext=" + opaqueContext);
        Collection<String> uuids = dao.find(componentId, opaqueContext);
        for (String uuid : uuids) {
            deleteDelayedInvocation(uuid);
        }
    }

    /* (non-Javadoc)
	 * @see org.sakaiproject.api.app.scheduler.ScheduledInvocationManager#findDelayedInvocations(java.lang.String, java.lang.String)
	 */
    @Transactional(propagation = REQUIRES_NEW)
    public DelayedInvocation[] findDelayedInvocations(String componentId, String opaqueContext) {
        log.debug("componentId=" + componentId + ", opaqueContext=" + opaqueContext);
        Collection<String> uuids = dao.find(componentId, opaqueContext);
        List<DelayedInvocation> invocations = new ArrayList<>();
        for (String uuid : uuids) {
            TriggerKey key = new TriggerKey(uuid, GROUP_NAME);
            try {
                Trigger trigger = schedulerFactory.getScheduler().getTrigger(key);
                if (trigger == null) {
                    log.error("Failed to trigger with key: {}", key);
                } else {
                    invocations.add(new DelayedInvocation(trigger.getKey().getName(), trigger.getNextFireTime(), key.getName(), opaqueContext));
                }
            } catch (SchedulerException e) {
                log.warn("Problem finding delayed invocations.", e);
                return null;
            }
        }
        return invocations.toArray(new DelayedInvocation[] {});
    }

    /**
     * This is used to cleanup the aditional data after the trigger has fired.
     */
    private clreplaced ContextTriggerListener extends TriggerListenerSupport {

        ContextTriggerListener(String name) {
            this.name = name;
        }

        private String name;

        @Override
        public String getName() {
            return name;
        }

        public void triggerComplete(Trigger trigger, JobExecutionContext context, Trigger.CompletedExecutionInstruction triggerInstructionCode) {
            // Check it's one of ours
            if (GROUP_NAME.equals(trigger.getKey().getGroup())) {
                String contextId = trigger.getJobDataMap().getString(CONTEXT_ID);
                if (contextId == null) {
                    log.warn("One of our triggers ({}) didn't have a context ID", trigger.getKey());
                } else {
                    dao.remove(trigger.getJobKey().getName(), contextId);
                }
            }
        }
    }
}

19 View Complete Implementation : DB2.java
Copyright Apache License 2.0
Author : AsuraTeam
public static void main(String[] args) throws Exception {
    SchedulerFactory sf = new StdSchedulerFactory("E:\\git-working\\asura-framework\\asura\\asura-dubbo\\src\\test\\java\\com\\asura\\test\\quartz.properties");
    Scheduler sched = sf.getScheduler();
    sched.start();
}

19 View Complete Implementation : TaskSchedulerFactory.java
Copyright Apache License 2.0
Author : yamingd
// ---------------------------------------------------------------------
// Implementation of InitializingBean interface
// ---------------------------------------------------------------------
public void afterPropertiesSet() throws Exception {
    if (this.dataSource == null && this.nonTransactionalDataSource != null) {
        this.dataSource = this.nonTransactionalDataSource;
    }
    if (this.applicationContext != null && this.resourceLoader == null) {
        this.resourceLoader = this.applicationContext;
    }
    // Create SchedulerFactory instance.
    SchedulerFactory schedulerFactory = (SchedulerFactory) BeanUtils.instantiateClreplaced(this.schedulerFactoryClreplaced);
    initSchedulerFactory(schedulerFactory);
    if (this.resourceLoader != null) {
        // Make given ResourceLoader available for SchedulerFactory configuration.
        configTimeResourceLoaderHolder.set(this.resourceLoader);
    }
    if (this.taskExecutor != null) {
        // Make given TaskExecutor available for SchedulerFactory configuration.
        configTimeTaskExecutorHolder.set(this.taskExecutor);
    }
    if (this.dataSource != null) {
        // Make given DataSource available for SchedulerFactory configuration.
        configTimeDataSourceHolder.set(this.dataSource);
    }
    if (this.nonTransactionalDataSource != null) {
        // Make given non-transactional DataSource available for SchedulerFactory configuration.
        configTimeNonTransactionalDataSourceHolder.set(this.nonTransactionalDataSource);
    }
    // Get Scheduler instance from SchedulerFactory.
    try {
        this.scheduler = createScheduler(schedulerFactory, this.schedulerName);
        populateSchedulerContext();
        if (!this.jobFactorySet && !(this.scheduler instanceof RemoteScheduler)) {
            // Use AdaptableJobFactory as default for a local Scheduler, unless when
            // explicitly given a null value through the "jobFactory" bean property.
            this.jobFactory = new AdaptableJobFactory();
        }
        if (this.jobFactory != null) {
            if (this.jobFactory instanceof SchedulerContextAware) {
                ((SchedulerContextAware) this.jobFactory).setSchedulerContext(this.scheduler.getContext());
            }
            this.scheduler.setJobFactory(this.jobFactory);
        }
    } finally {
        if (this.resourceLoader != null) {
            configTimeResourceLoaderHolder.set(null);
        }
        if (this.taskExecutor != null) {
            configTimeTaskExecutorHolder.set(null);
        }
        if (this.dataSource != null) {
            configTimeDataSourceHolder.set(null);
        }
        if (this.nonTransactionalDataSource != null) {
            configTimeNonTransactionalDataSourceHolder.set(null);
        }
    }
    registerListeners();
    registerJobsAndTriggers();
}

19 View Complete Implementation : QuartzUtil.java
Copyright Apache License 2.0
Author : fixteam
/**
 * 创建定时任务工厂
 * @return
 */
public static SchedulerFactory createSchedulerFactory() {
    SchedulerFactory sf = new StdSchedulerFactory();
    return sf;
}

19 View Complete Implementation : SfbestSchedulerContainer.java
Copyright Apache License 2.0
Author : AsuraTeam
/**
 * 启动QuartzScheduler
 *
 * @author zhangshaobin
 * @created 2013-1-4 下午4:11:50
 */
public void start() throws BusinessException {
    try {
        SchedulerFactory sf = new StdSchedulerFactory("quartz.properties");
        scheduler = sf.getScheduler();
        scheduler.start();
        logger.info(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]").format(new Date()) + " Quartz started!");
    } catch (SchedulerException e) {
        logger.error("启动Quartz出错:" + e.getMessage(), e.getCause());
        throw new BusinessException(e.getMessage(), e.getCause());
    }
}

19 View Complete Implementation : JobScheduler.java
Copyright GNU General Public License v2.0
Author : 52North
private void createDefaultScheduler() {
    try {
        SchedulerFactory sf = new StdSchedulerFactory();
        scheduler = sf.getScheduler();
    } catch (SchedulerException e) {
        LOGGER.error("Could create scheduler.", e);
    }
}

19 View Complete Implementation : MongoSubscription.java
Copyright Apache License 2.0
Author : JaewookByun
/**
 * Copyright (C) 2014-2016 Jaewook Byun
 *
 * This project is part of Oliot open source (http://oliot.org). Oliot EPCIS
 * v1.2.x is Java Web Service complying with Electronic Product Code Information
 * Service (EPCIS) v1.2.
 *
 * @author Jaewook Byun, Ph.D student
 *
 *         Korea Advanced Insreplacedute of Science and Technology (KAIST)
 *
 *         Real-time Embedded System Laboratory(RESL)
 *
 *         [email protected], [email protected]
 */
public clreplaced MongoSubscription {

    public static SchedulerFactory schedFact;

    public static Scheduler sched;

    public void init() {
        try {
            schedFact = new org.quartz.impl.StdSchedulerFactory();
            sched = schedFact.getScheduler();
            if (sched.isStarted() == false)
                sched.start();
            MongoCollection<BsonDoreplacedent> collection = Configuration.mongoDatabase.getCollection("Subscription", BsonDoreplacedent.clreplaced);
            Iterator<BsonDoreplacedent> subIterator = collection.find(BsonDoreplacedent.clreplaced).iterator();
            MongoQueryService queryService = new MongoQueryService();
            while (subIterator.hasNext()) {
                BsonDoreplacedent sub = subIterator.next();
                SubscriptionType subscription = new SubscriptionType(sub);
                if (subscription.getSchedule() != null && subscription.getTrigger() == null) {
                    queryService.addScheduleToQuartz(subscription);
                } else if (subscription.getSchedule() == null && subscription.getTrigger() != null) {
                    TriggerEngine.addTriggerSubscription(sub.getString("subscriptionID").getValue(), subscription);
                }
            }
        } catch (SchedulerException e) {
            Configuration.logger.log(Level.ERROR, e.toString());
        }
    }
}

18 View Complete Implementation : Executor.java
Copyright GNU Affero General Public License v3.0
Author : exense
public clreplaced Executor {

    private final Logger logger = LoggerFactory.getLogger(Executor.clreplaced);

    private Scheduler scheduler;

    private SchedulerFactory schedulerFactory;

    private ExecutionRunnableFactory executionRunnableFactory;

    private Configuration configuration;

    public Executor(GlobalContext globalContext) {
        super();
        configuration = globalContext.getConfiguration();
        try {
            Properties props = getProperties();
            executionRunnableFactory = new ExecutionRunnableFactory(globalContext);
            schedulerFactory = new StdSchedulerFactory(props);
            scheduler = schedulerFactory.getScheduler();
            scheduler.setJobFactory(new ExecutionJobFactory(globalContext, executionRunnableFactory));
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    private Properties getProperties() {
        Properties props = new Properties();
        props.put("org.quartz.threadPool.threadCount", configuration.getProperty("tec.executor.threads", "10"));
        return props;
    }

    public void shutdown() {
        try {
            scheduler.shutdown(true);
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    public void start() {
        try {
            scheduler.start();
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    public void deleteSchedule(ExecutiontTaskParameters task) {
        JobKey key = new JobKey(task.getId().toString());
        try {
            scheduler.deleteJob(key);
        } catch (SchedulerException e) {
            logger.error("An error occurred while removing task from scheduler: " + task);
            throw new RuntimeException(e);
        }
    }

    public void validate(ExecutiontTaskParameters task) {
        CronScheduleBuilder.cronSchedule(task.getCronExpression());
    }

    public boolean schedule(ExecutiontTaskParameters task) {
        JobKey key = new JobKey(task.getId().toString());
        try {
            if (scheduler.checkExists(key)) {
                deleteSchedule(task);
            }
        } catch (SchedulerException e) {
            logger.error("An error occurred while checking if task exists in scheduler: " + task);
            throw new RuntimeException(e);
        }
        Trigger trigger = TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule(task.getCronExpression())).build();
        JobDetail job = buildScheduledJob(task);
        scheduleJob(trigger, job);
        return trigger.mayFireAgain();
    }

    public String execute(ExecutionParameters executionParameters) {
        return execute(executionParameters, null);
    }

    public String execute(ExecutionParameters executionParameters, String executionTaskId) {
        Execution execution = executionRunnableFactory.createExecution(executionParameters, executionTaskId);
        Trigger trigger = TriggerBuilder.newTrigger().startNow().build();
        String executionID = execution.getId().toString();
        JobDetail job = buildSingleJob(executionID);
        scheduleJob(trigger, job);
        return executionID;
    }

    private void scheduleJob(Trigger trigger, JobDetail job) {
        try {
            scheduler.scheduleJob(job, trigger);
        } catch (SchedulerException e) {
            throw new RuntimeException("An unexpected error occurred while scheduling job " + job.toString(), e);
        }
    }

    protected static final String EXECUTION_PARAMETERS = "ExecutionParameters";

    protected static final String EXECUTION_ID = "ExecutionID";

    protected static final String EXECUTION_TASK_ID = "ExecutionTaskID";

    private JobDetail buildSingleJob(String executionID) {
        JobDataMap data = new JobDataMap();
        data.put(EXECUTION_ID, executionID);
        return JobBuilder.newJob().ofType(ExecutionJob.clreplaced).usingJobData(data).build();
    }

    private JobDetail buildScheduledJob(ExecutiontTaskParameters task) {
        JobDataMap data = new JobDataMap();
        data.put(EXECUTION_TASK_ID, task.getId().toString());
        data.put(EXECUTION_PARAMETERS, task.getExecutionsParameters());
        return JobBuilder.newJob().ofType(ExecutionJob.clreplaced).withIdenreplacedy(task.getId().toString()).usingJobData(data).build();
    }

    public List<ExecutionRunnable> getCurrentExecutions() {
        List<JobExecutionContext> excutingJobs;
        try {
            excutingJobs = scheduler.getCurrentlyExecutingJobs();
        } catch (SchedulerException e) {
            throw new RuntimeException("Unexepected error occurred while getting executing jobs", e);
        }
        List<ExecutionRunnable> result = new ArrayList<ExecutionRunnable>(excutingJobs.size());
        for (JobExecutionContext jobContext : excutingJobs) {
            result.add(((ExecutionJob) jobContext.getJobInstance()).getRunnable());
        }
        return result;
    }

    public List<ExecutiontTaskParameters> getScheduledExecutions() {
        List<ExecutiontTaskParameters> result = new ArrayList<>();
        try {
            for (String group : scheduler.getJobGroupNames()) {
                GroupMatcher<JobKey> matcher = GroupMatcher.groupEquals(group);
                for (JobKey jobKey : scheduler.getJobKeys(matcher)) {
                    JobDetail job = scheduler.getJobDetail(jobKey);
                    JobDataMap data = job.getJobDataMap();
                    ExecutionParameters params = (ExecutionParameters) data.get(EXECUTION_PARAMETERS);
                    List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
                    for (Trigger trigger : triggers) {
                        if (trigger instanceof CronTrigger) {
                            ExecutiontTaskParameters p = new ExecutiontTaskParameters(params, ((CronTrigger) trigger).getCronExpression());
                            result.add(p);
                        }
                    }
                }
            }
        } catch (SchedulerException e) {
            logger.error("An error occurred while getting scheduled jobs", e);
        }
        return result;
    }
}

18 View Complete Implementation : QuartzUtil.java
Copyright Apache License 2.0
Author : fixteam
/**
 * 根据任务工厂拿到定时任务
 * @param schedulerFactory 任务工厂
 * @return
 */
public static Scheduler getScheduler(SchedulerFactory schedulerFactory) {
    Scheduler scheduler = null;
    try {
        scheduler = schedulerFactory.getScheduler();
    } catch (SchedulerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return scheduler;
}

18 View Complete Implementation : QuartzUtil.java
Copyright Apache License 2.0
Author : fixteam
/**
 * 根据传入的属性文件创建定时任务工厂
 * @param props
 * @return
 */
public static SchedulerFactory createSchedulerFactory(Properties props) {
    SchedulerFactory sf = null;
    try {
        sf = new StdSchedulerFactory(props);
    } catch (SchedulerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return sf;
}

18 View Complete Implementation : QuartzUtil.java
Copyright Apache License 2.0
Author : FoxBPM
/**
 * 根据传入的属性文件创建定时任务工厂
 *
 * @param props
 * @return
 */
public final static SchedulerFactory createSchedulerFactory(Properties props) {
    SchedulerFactory sf = null;
    try {
        sf = new StdSchedulerFactory(props);
    } catch (Exception e) {
        throw new FoxBPMException("QuartzUtil 创建 SchedulerFactory出问题", e);
    }
    return sf;
}

18 View Complete Implementation : QuartzUtil.java
Copyright Apache License 2.0
Author : FoxBPM
/**
 * 根据任务工厂拿到定时任务
 *
 * @param schedulerFactory
 *            任务工厂
 * @return
 */
public final static Scheduler getScheduler(SchedulerFactory schedulerFactory) {
    Scheduler scheduler = null;
    try {
        scheduler = schedulerFactory.getScheduler();
    } catch (Exception e) {
        throw new FoxBPMException("QuartzUtil 创建 Scheduler出问题", e);
    }
    return scheduler;
}

18 View Complete Implementation : SchedulerUtility.java
Copyright Apache License 2.0
Author : helicalinsight
/**
 * Create instance of SchedulerFactory
 *
 * @author Prashansa
 * @see ScheduleProcess
 */
public clreplaced SchedulerUtility {

    private static final Logger logger = LoggerFactory.getLogger(SchedulerUtility.clreplaced);

    private static Scheduler scheduler = null;

    private volatile static SchedulerFactory schedulerFactory = new StdSchedulerFactory();

    public static Scheduler getInstance() {
        if (scheduler == null) {
            try {
                synchronized (SchedulerUtility.clreplaced) {
                    if (scheduler == null) {
                        scheduler = schedulerFactory.getScheduler();
                    }
                }
            } catch (SchedulerException ex) {
                logger.error("Error: ", ex);
            }
        }
        return scheduler;
    }
}

18 View Complete Implementation : QuartzConfig.java
Copyright Apache License 2.0
Author : helloworldtang
/**
 * quartz job即没有报错,也不执行。可以会以下两个方面进行排查:
 * (1)OutOfMemory
 * (2)增大threadCount
 * (3)所有的job,listener都要try catch(Exception e)
 *
 * @param springJobFactory
 * @return
 * @throws SchedulerException
 */
@Bean
public Scheduler scheduler(SpringJobFactory springJobFactory) throws SchedulerException {
    /**
     * 如果不使用下面的的Properties配置,
     * 默认会使用quartz.2.3.2.jar中的org.quartz.quartz.properties文件
     */
    SchedulerFactory schedulerFactory = new StdSchedulerFactory(quartzProperties());
    Scheduler scheduler = schedulerFactory.getScheduler();
    scheduler.setJobFactory(springJobFactory);
    scheduler.start();
    return scheduler;
}

18 View Complete Implementation : SchedulerMainService.java
Copyright BSD 2-Clause "Simplified" License
Author : iotoasis
@Service
public clreplaced SchedulerMainService implements ApplicationContextAware {

    private static ApplicationContext context;

    private SchedulerFactory schedulFactoty = null;

    private Scheduler scheduler = null;

    private JobDetail jobDetail = null;

    private CronTrigger trigger = null;

    private SchDTO[] schDTO;

    private Log log = LogFactory.getLog(this.getClreplaced());

    public void JobInit() throws Exception {
        try {
            if (scheduler != null && scheduler.isStarted())
                return;
            schedulFactoty = new StdSchedulerFactory();
            scheduler = schedulFactoty.getScheduler();
            scheduler.start();
            JobRegist();
        } catch (Exception e) {
            throw e;
        }
    }

    public Scheduler getScheduler() throws Exception {
        if (scheduler == null) {
            schedulFactoty = new StdSchedulerFactory();
            scheduler = schedulFactoty.getScheduler();
        }
        return scheduler;
    }

    public void JobRegist() throws Exception {
        Clreplaced c = null;
        // 등록할 스케줄 정보 설정
        setSchList();
        for (int j = 0; j < schDTO.length; j++) {
            try {
                c = Clreplaced.forName(schDTO[j].getTask_clreplaced());
                jobDetail = new JobDetail(schDTO[j].getTask_id(), schDTO[j].getTask_group_id(), c);
                trigger = new CronTrigger(schDTO[j].getTask_id(), schDTO[j].getTask_group_id());
                trigger.setCronExpression(schDTO[j].getTask_expression());
                scheduler.scheduleJob(jobDetail, trigger);
            } catch (Exception e) {
                throw e;
            }
        }
    }

    // 상태보기
    public void statusSchList() throws Exception {
        setSchList();
        for (int j = 0; j < schDTO.length; j++) {
            log.debug("trigger[" + j + "] : " + scheduler.getTriggerState(schDTO[j].getTask_id(), schDTO[j].getTask_group_id()) + " (not initiated:-1, running/standby:0,  paused:1)");
        }
    }

    // 상태값
    public String getStatusList() throws Exception {
        StringBuffer sb = new StringBuffer();
        setSchList();
        for (int j = 0; j < schDTO.length; j++) {
            sb.append("trigger[");
            sb.append(j);
            sb.append("](group_id:");
            sb.append(schDTO[j].getTask_group_id());
            sb.append(",");
            sb.append(" task_id:");
            sb.append(schDTO[j].getTask_id());
            sb.append(") : ");
            sb.append(scheduler.getTriggerState(schDTO[j].getTask_id(), schDTO[j].getTask_group_id()));
            sb.append(" (not initiated:-1, running/standby:0, paused:1)");
            if ((j + 1) != schDTO.length) {
                sb.append("<br>");
            }
        }
        return sb.toString();
    }

    // pause
    public void pauseSch() throws Exception {
        setSchList();
        for (int j = 0; j < schDTO.length; j++) {
            scheduler.pauseJob(schDTO[j].getTask_id(), schDTO[j].getTask_group_id());
            log.debug("[" + j + "] paused......");
        }
    }

    // resume
    public void resumeSch() throws Exception {
        setSchList();
        for (int j = 0; j < schDTO.length; j++) {
            scheduler.resumeJob(schDTO[j].getTask_id(), schDTO[j].getTask_group_id());
            log.debug("[" + j + "] resumed......");
        }
    }

    // standby
    public void standbySch() throws Exception {
        setSchList();
        scheduler.standby();
        log.debug("scheduler is in state of standby ......");
    }

    // start
    public void startSch() throws Exception {
        setSchList();
        scheduler.start();
        log.debug("scheduler is in state of start ......");
    }

    // shutdown
    public void shutdown() throws Exception {
        scheduler.shutdown();
    }

    private void setSchList() throws Exception {
        if (schDTO != null)
            return;
        // 스케줄정보 가져오기
        List<SchDTO> schList = new ArrayList<SchDTO>();
        try {
            SchService schService = getContext().getBean(SchService.clreplaced);
            schList = schService.selectList();
        } catch (SQLNonTransientConnectionException e) {
            // 쿼리파이프가 깨짐, 여러번 retry하면 접속됨 혹은 gc해서 restart하게함(?)
            System.gc();
        } catch (Exception e) {
            throw e;
        }
        schDTO = new SchDTO[schList.size()];
        for (int i = 0; i < schList.size(); i++) {
            schDTO[i] = schList.get(i);
            log.debug("schDTO[" + i + "] in SchedulerMainService================>" + schDTO[i].toString());
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static ApplicationContext getContext() {
        return context;
    }
}

18 View Complete Implementation : SchedulerFactoryBean.java
Copyright Apache License 2.0
Author : langtianya
// ---------------------------------------------------------------------
// Implementation of InitializingBean interface
// ---------------------------------------------------------------------
@Override
public void afterPropertiesSet() throws Exception {
    if (this.dataSource == null && this.nonTransactionalDataSource != null) {
        this.dataSource = this.nonTransactionalDataSource;
    }
    if (this.applicationContext != null && this.resourceLoader == null) {
        this.resourceLoader = this.applicationContext;
    }
    // Create SchedulerFactory instance...
    SchedulerFactory schedulerFactory = BeanUtils.instantiateClreplaced(this.schedulerFactoryClreplaced);
    initSchedulerFactory(schedulerFactory);
    if (this.resourceLoader != null) {
        // Make given ResourceLoader available for SchedulerFactory configuration.
        configTimeResourceLoaderHolder.set(this.resourceLoader);
    }
    if (this.taskExecutor != null) {
        // Make given TaskExecutor available for SchedulerFactory configuration.
        configTimeTaskExecutorHolder.set(this.taskExecutor);
    }
    if (this.dataSource != null) {
        // Make given DataSource available for SchedulerFactory configuration.
        configTimeDataSourceHolder.set(this.dataSource);
    }
    if (this.nonTransactionalDataSource != null) {
        // Make given non-transactional DataSource available for SchedulerFactory configuration.
        configTimeNonTransactionalDataSourceHolder.set(this.nonTransactionalDataSource);
    }
    // Get Scheduler instance from SchedulerFactory.
    try {
        this.scheduler = createScheduler(schedulerFactory, this.schedulerName);
        populateSchedulerContext();
        if (!this.jobFactorySet && !(this.scheduler instanceof RemoteScheduler)) {
            // Use AdaptableJobFactory as default for a local Scheduler, unless when
            // explicitly given a null value through the "jobFactory" bean property.
            this.jobFactory = new AdaptableJobFactory();
        }
        if (this.jobFactory != null) {
            if (this.jobFactory instanceof SchedulerContextAware) {
                ((SchedulerContextAware) this.jobFactory).setSchedulerContext(this.scheduler.getContext());
            }
            this.scheduler.setJobFactory(this.jobFactory);
        }
    } finally {
        if (this.resourceLoader != null) {
            configTimeResourceLoaderHolder.remove();
        }
        if (this.taskExecutor != null) {
            configTimeTaskExecutorHolder.remove();
        }
        if (this.dataSource != null) {
            configTimeDataSourceHolder.remove();
        }
        if (this.nonTransactionalDataSource != null) {
            configTimeNonTransactionalDataSourceHolder.remove();
        }
    }
    registerListeners();
    registerJobsAndTriggers();
}

18 View Complete Implementation : JobScheduler.java
Copyright GNU Affero General Public License v3.0
Author : mosabsalih
/**
 * Singleton wrapper to provide easy access to the Quartz Scheduler. Used to schedule
 * all of jBilling's batch processes and {@link com.sapienter.jbilling.server.process.task.IScheduledTask}
 * plug-ins.
 *
 * @author Brian Cowdery
 * @since 02-02-2010
 */
public clreplaced JobScheduler {

    private static final Logger LOG = Logger.getLogger(JobScheduler.clreplaced);

    private static JobScheduler instance = null;

    private SchedulerFactory factory = null;

    private Scheduler scheduler = null;

    private JobScheduler() {
        factory = new StdSchedulerFactory();
    }

    public static JobScheduler getInstance() {
        if (instance == null)
            instance = new JobScheduler();
        return instance;
    }

    public Scheduler getScheduler() {
        if (scheduler == null) {
            try {
                scheduler = factory.getScheduler();
            } catch (SchedulerException e) {
                LOG.error("Exception occurred retrieving the scheduler instance.", e);
            }
        }
        return scheduler;
    }

    public void start() {
        try {
            getScheduler().start();
        } catch (SchedulerException e) {
            LOG.error("Exception occurred starting the scheduler.", e);
        }
    }

    public void shutdown() {
        try {
            getScheduler().shutdown();
        } catch (SchedulerException e) {
        // swallow
        }
    }
}

18 View Complete Implementation : JobScheduler.java
Copyright GNU Affero General Public License v3.0
Author : opensourceBIM
public clreplaced JobScheduler {

    private static final Logger LOGGER = LoggerFactory.getLogger(JobScheduler.clreplaced);

    // 30 minutes
    private static final int COMPARE_RESULT_CLEAN_INTERVAL_MILLIS = 30 * 60 * 1000;

    // 1 minute
    private static final int LONG_ACTION_MANAGER_CLEANUP_INTERVAL_MILLIS = 1 * 60 * 1000;

    private SchedulerFactory sf;

    private Scheduler sched;

    public static clreplaced CompareResultCacheCleaner implements Job {

        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            try {
                BimServer bimServer = (BimServer) (jobExecutionContext.getScheduler().getContext().get("bimserver"));
                bimServer.getCompareCache().cleanup();
            } catch (SchedulerException e) {
                LOGGER.error("", e);
            }
        }
    }

    public static clreplaced LongActionManagerCleaner implements Job {

        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            try {
                BimServer bimServer = (BimServer) (jobExecutionContext.getScheduler().getContext().get("bimserver"));
                bimServer.getLongActionManager().cleanup();
            } catch (SchedulerException e) {
                LOGGER.error("", e);
            }
        }
    }

    public JobScheduler(BimServer bimServer) {
        try {
            Properties properties = new Properties();
            String instanceName = "UniqueName" + Math.random();
            properties.setProperty("org.quartz.threadPool.clreplaced", "org.quartz.simpl.SimpleThreadPool");
            properties.setProperty("org.quartz.threadPool.threadCount", "1");
            properties.setProperty(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, instanceName);
            sf = new StdSchedulerFactory(properties);
            sched = sf.getScheduler();
            sched.getContext().put("bimserver", bimServer);
        } catch (SchedulerException e) {
            LOGGER.error("", e);
        }
    }

    public void start() {
        try {
            addRecurringJob(CompareResultCacheCleaner.clreplaced, COMPARE_RESULT_CLEAN_INTERVAL_MILLIS);
            addRecurringJob(LongActionManagerCleaner.clreplaced, LONG_ACTION_MANAGER_CLEANUP_INTERVAL_MILLIS);
            sched.start();
        } catch (SchedulerException e) {
            LOGGER.error("", e);
        }
    }

    private void addRecurringJob(Clreplaced<? extends Job> clreplaced1, int intervalMillis) throws SchedulerException {
        SimpleTrigger trigger = newTrigger().withIdenreplacedy("group1", clreplaced1.getSimpleName()).withSchedule(simpleSchedule().withIntervalInMilliseconds(intervalMillis).repeatForever()).build();
        JobDetail job = newJob(clreplaced1).withIdenreplacedy("group1", clreplaced1.getSimpleName()).build();
        sched.scheduleJob(job, trigger);
    }

    public void close() {
        try {
            sched.shutdown();
        } catch (SchedulerException e) {
            LOGGER.error("", e);
        }
    }
}

18 View Complete Implementation : QuartzManager.java
Copyright Apache License 2.0
Author : quartzweb
/**
 * 操作quartz的scheduler,job,triger核心管理类
 *
 * @author quxiucheng [[email protected]]
 */
public clreplaced QuartzManager {

    private final static QuartzManager instance = new QuartzManager();

    private QuartzManager() {
    }

    public static QuartzManager getInstance() {
        return instance;
    }

    /**
     * 是否查找Scheduler仓库,默认true
     */
    private boolean lookupSchedulerRepository = true;

    /**
     * 是否启用默认Scheduler,默认true
     * 默认Scheduler是从defualtSchedulerFactory获取
     */
    private boolean useDefaultScheduler = true;

    /**
     * 默认Scheduler工厂
     */
    private SchedulerFactory defualtSchedulerFactory = new StdSchedulerFactory();

    /**
     * 管理的Scheduler集合
     */
    private List<Scheduler> schedulers = new ArrayList<Scheduler>();

    /**
     * schedulerMap方便查找
     */
    private Map<String, Scheduler> schedulerMap = new HashMap<String, Scheduler>();

    private boolean init = false;

    /**
     * 获取 是否查找Scheduler仓库,默认true
     *
     * @return lookupSchedulerRepository 是否查找Scheduler仓库,默认true
     */
    public boolean isLookupSchedulerRepository() {
        return this.lookupSchedulerRepository;
    }

    /**
     * 设置 是否查找Scheduler仓库,默认true
     *
     * @param lookupSchedulerRepository 是否查找Scheduler仓库,默认true
     */
    public void setLookupSchedulerRepository(boolean lookupSchedulerRepository) throws SchedulerException {
        this.lookupSchedulerRepository = lookupSchedulerRepository;
    }

    /**
     * 获取 是否启用默认Scheduler,默认true默认Scheduler是从defualtSchedulerFactory获取
     *
     * @return useDefaultScheduler 是否启用默认Scheduler,默认true默认Scheduler是从defualtSchedulerFactory获取
     */
    public boolean isUseDefaultScheduler() {
        return this.useDefaultScheduler;
    }

    /**
     * 设置 是否启用默认Scheduler,默认true默认Scheduler是从defualtSchedulerFactory获取
     *
     * @param useDefaultScheduler 是否启用默认Scheduler,默认true默认Scheduler是从defualtSchedulerFactory获取
     */
    public void setUseDefaultScheduler(boolean useDefaultScheduler) throws SchedulerException {
        this.useDefaultScheduler = useDefaultScheduler;
    }

    /**
     * 获取 默认Scheduler工厂
     *
     * @return defualtSchedulerFactory 默认Scheduler工厂
     */
    public SchedulerFactory getDefualtSchedulerFactory() {
        return this.defualtSchedulerFactory;
    }

    /**
     * 设置 默认Scheduler工厂
     *
     * @param defualtSchedulerFactory 默认Scheduler工厂
     */
    public void setDefualtSchedulerFactory(SchedulerFactory defualtSchedulerFactory) throws SchedulerException {
        this.defualtSchedulerFactory = defualtSchedulerFactory;
    }

    /**
     * 设置 管理的Scheduler集合
     *
     * @param schedulers 管理的Scheduler集合
     */
    public void setSchedulers(List<Scheduler> schedulers) throws SchedulerException {
        this.schedulers = schedulers;
    }

    /**
     * 注册获取schedulers
     * 所有设置后调用该方法
     *
     * @throws SchedulerException 异常
     */
    private void registerSchedulers() throws SchedulerException {
        // 未初始化,执行初始化注册代码
        if (!init) {
            if (schedulers == null) {
                schedulers = new ArrayList<Scheduler>();
            }
            // 将名称转换成map方便查找
            Map<String, String> schedulerNameMap = new HashMap<String, String>();
            for (Scheduler scheduler : this.schedulers) {
                schedulerNameMap.put(scheduler.getSchedulerName(), scheduler.getSchedulerName());
            }
            // 是否查找仓库
            if (this.lookupSchedulerRepository) {
                // 仓库中所有的Scheduler集合
                Collection<Scheduler> allRepositoryScheduler = QuartzUtils.getAllScheduler();
                for (Scheduler repositoryScheduler : allRepositoryScheduler) {
                    // 在scheduler中不存在添加
                    if (StringUtils.isEmpty(schedulerNameMap.get(repositoryScheduler.getSchedulerName()))) {
                        this.schedulers.add(repositoryScheduler);
                    }
                }
            }
            // 是否启动默认scheduler
            if (this.useDefaultScheduler) {
                Scheduler defualtScheduler = defualtSchedulerFactory.getScheduler();
                if (StringUtils.isEmpty(schedulerNameMap.get(defualtScheduler.getSchedulerName()))) {
                    this.schedulers.add(defualtScheduler);
                }
            }
            // 初始化schedulerMap信息
            this.schedulerMap = new HashMap<String, Scheduler>();
            for (Scheduler scheduler : this.schedulers) {
                this.schedulerMap.put(scheduler.getSchedulerName(), scheduler);
            }
            List<Scheduler> schedulersTemp = new ArrayList<Scheduler>();
            for (Map.Entry<String, Scheduler> schedulerEntry : this.schedulerMap.entrySet()) {
                Scheduler value = schedulerEntry.getValue();
                schedulersTemp.add(value);
            }
            this.schedulers = schedulersTemp;
            init = true;
        }
    }

    /**
     * 当scheduler唯一时获取scheduler
     *
     * @return scheduler对象
     * @throws SchedulerException 异常
     */
    public Scheduler getScheduler() throws SchedulerException {
        registerSchedulers();
        if (this.schedulers.size() > 1) {
            throw new NonUniqueResultException("[org.quartz.Scheduler] did not return a unique result");
        } else {
            return schedulers.get(0);
        }
    }

    /**
     * 根据scheduler名称获取
     *
     * @param schedulerName 名称
     * @return scheduler对象
     * @throws SchedulerException 异常
     */
    public Scheduler getScheduler(String schedulerName) throws SchedulerException {
        registerSchedulers();
        replacedert.notEmpty(schedulerName, "schedulerName can not be empty");
        return schedulerMap.get(schedulerName);
    }

    /**
     * 根据名称获取scheduler,如果没有则报错
     * @param schedulerName
     * @return
     * @throws IllegalArgumentException 出问题时报错
     */
    public Scheduler getreplacedertScheduler(String schedulerName) throws SchedulerException {
        registerSchedulers();
        replacedert.notEmpty(schedulerName, "schedulerName can not be empty");
        Scheduler scheduler = schedulerMap.get(schedulerName);
        if (scheduler == null) {
            throw new IllegalArgumentException(schedulerName + " is not exists");
        }
        return scheduler;
    }

    /**
     * 获取 管理的Scheduler集合
     *
     * @return schedulers 管理的Scheduler集合
     */
    public List<Scheduler> getSchedulers() throws SchedulerException {
        registerSchedulers();
        // 不可改变
        return java.util.Collections.unmodifiableList(this.schedulers);
    }

    /**
     * 核查scheduler是否存在
     * @param schedulerName
     * @return
     */
    public boolean existsScheduler(String schedulerName) throws SchedulerException {
        Scheduler scheduler = this.getScheduler(schedulerName);
        if (scheduler == null) {
            return false;
        }
        return true;
    }

    /**
     * 获取job
     * @param schedulerName
     * @param jobName
     * @param jobGroup
     * @return
     * @throws SchedulerException
     */
    public JobDetail getJob(String schedulerName, String jobName, String jobGroup) throws SchedulerException {
        replacedert.notEmpty(jobName, "jobName can not be empty");
        replacedert.notEmpty(jobGroup, "jobGroup can not be empty");
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        JobDetail jobDetail = QuartzUtils.getJob(scheduler, jobName, jobGroup);
        return jobDetail;
    }

    /**
     * 获取某个scheduler的job详情集合
     * @param schedulerName
     * @return
     * @throws SchedulerException
     */
    public List<JobDetail> getAllJobsOfScheduler(String schedulerName) throws SchedulerException {
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        List<JobDetail> allJobsOfScheduler = QuartzUtils.getAllJobsOfScheduler(scheduler);
        return allJobsOfScheduler;
    }

    /**
     * 获取所有的job详情集合
     * @return
     * @throws SchedulerException
     */
    public List<JobDetail> getAllJobs() throws SchedulerException {
        List<JobDetail> allJobs = new ArrayList<JobDetail>();
        List<Scheduler> schedulers = this.getSchedulers();
        for (Scheduler scheduler : schedulers) {
            List<JobDetail> allJobsOfScheduler = QuartzUtils.getAllJobsOfScheduler(scheduler);
            allJobs.addAll(allJobsOfScheduler);
        }
        return allJobs;
    }

    /**
     * 获取job的trigger信息
     * @param schedulerName
     * @param jobName
     * @param jobGroup
     * @return
     * @throws SchedulerException
     */
    public List<? extends Trigger> getTriggersOfJob(String schedulerName, String jobName, String jobGroup) throws SchedulerException {
        replacedert.notEmpty(jobName, "jobName can not be empty");
        replacedert.notEmpty(jobGroup, "jobGroup can not be empty");
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        List<? extends Trigger> triggersOfJob = QuartzUtils.getTriggersOfJob(jobName, jobGroup, scheduler);
        return triggersOfJob;
    }

    /**
     * 获取所有的Trigger
     * @param schedulerName
     * @return
     * @throws SchedulerException
     */
    public List<? extends Trigger> getAllTriggersOfScheduler(String schedulerName) throws SchedulerException {
        List<Trigger> triggersOfScheduler = new ArrayList<Trigger>();
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        List<JobDetail> jobDetails = getAllJobsOfScheduler(schedulerName);
        for (JobDetail jobDetail : jobDetails) {
            List<? extends Trigger> triggersOfJob = QuartzUtils.getTriggersOfJob(jobDetail, scheduler);
            triggersOfScheduler.addAll(triggersOfJob);
        }
        return triggersOfScheduler;
    }

    /**
     * 获取全部trigger
     * @return
     * @throws SchedulerException
     */
    public List<? extends Trigger> getAllTriggers() throws SchedulerException {
        List<Trigger> triggers = new ArrayList<Trigger>();
        List<Scheduler> schedulers = this.getSchedulers();
        for (Scheduler scheduler : schedulers) {
            List<JobDetail> jobDetails = getAllJobsOfScheduler(scheduler.getSchedulerName());
            List<Trigger> triggersOfScheduler = new ArrayList<Trigger>();
            for (JobDetail jobDetail : jobDetails) {
                List<? extends Trigger> triggersOfJob = QuartzUtils.getTriggersOfJob(jobDetail, scheduler);
                triggersOfScheduler.addAll(triggersOfJob);
            }
            triggers.addAll(triggersOfScheduler);
        }
        return triggers;
    }

    public Trigger getTrigger(String schedulerName, String triggerName, String triggerGroup) throws SchedulerException {
        replacedert.notEmpty(triggerName, "triggerName can not be empty");
        replacedert.notEmpty(triggerGroup, "triggerGroup can not be empty");
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        TriggerKey triggerKey = QuartzUtils.getTriggerKey(triggerName, triggerGroup);
        Trigger trigger = scheduler.getTrigger(triggerKey);
        return trigger;
    }

    public void runTrigger(String schedulerName, String triggerName, String triggerGroup) throws SchedulerException {
        Trigger trigger = getTrigger(schedulerName, triggerName, triggerGroup);
        replacedert.notNull(trigger, "trigger is not exist");
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        scheduler.triggerJob(trigger.getJobKey(), trigger.getJobDataMap());
    }

    /**
     * 启动全部
     * @throws SchedulerException
     */
    public void schedulerStart() throws SchedulerException {
        List<Scheduler> schedulers = this.getSchedulers();
        for (Scheduler scheduler : schedulers) {
            scheduler.start();
        }
    }

    /**
     * 启动
     * @param schedulerName
     * @throws SchedulerException
     */
    public void schedulerStart(String schedulerName) throws SchedulerException {
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        if (!scheduler.isStarted()) {
            scheduler.start();
        }
    }

    /**
     * 延时启动
     * @param schedulerName
     * @param delayed 延迟秒数
     * @throws SchedulerException
     */
    public void schedulerStart(String schedulerName, int delayed) throws SchedulerException {
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        if (!scheduler.isStarted()) {
            if (delayed <= 0) {
                scheduler.start();
            } else {
                scheduler.startDelayed(delayed);
            }
        }
    }

    public void schedulerShutdown(String schedulerName) throws SchedulerException {
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        if (!scheduler.isShutdown()) {
            scheduler.shutdown();
        }
    }

    public void schedulerShutdown(String schedulerName, boolean waitForJobsToComplete) throws SchedulerException {
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        if (!scheduler.isShutdown()) {
            List<JobDetail> allJobsOfScheduler = QuartzUtils.getAllJobsOfScheduler(scheduler);
            for (JobDetail jobDetail : allJobsOfScheduler) {
                QuartzUtils.pauseJob(jobDetail, scheduler);
            }
            if (waitForJobsToComplete) {
                scheduler.shutdown(waitForJobsToComplete);
            } else {
                scheduler.shutdown();
            }
        }
    }

    /**
     * 核查job是否存在
     * 存在 true
     * 存在 false
     * @param schedulerName
     * @param jobName
     * @param jobGroup
     * @return
     * @throws SchedulerException
     */
    public boolean existJob(String schedulerName, String jobName, String jobGroup) throws SchedulerException {
        replacedert.notEmpty(jobName, "jobName can not be empty");
        replacedert.notEmpty(jobGroup, "jobGroup can not be empty");
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        JobDetail jobDetail = QuartzUtils.getJob(scheduler, jobName, jobGroup);
        if (jobDetail == null) {
            return false;
        }
        return true;
    }

    /**
     * 核查触发器是否存在
     * @param schedulerName
     * @param triggerName
     * @param triggerGroup
     * @return
     */
    public boolean existTrigger(String schedulerName, String triggerName, String triggerGroup) throws SchedulerException {
        replacedert.notEmpty(triggerName, "triggerName can not be empty");
        replacedert.notEmpty(triggerGroup, "triggerGroup can not be empty");
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        return QuartzUtils.checkTriggerExists(triggerName, triggerGroup, scheduler);
    }

    /**
     * 添加job
     *
     * @param schedulerName
     * @param jobDetail
     * @return
     * @throws SchedulerException
     */
    public void addJob(String schedulerName, JobDetail jobDetail, boolean replace) throws SchedulerException {
        replacedert.notEmpty(schedulerName, "schedulerName can not be empty");
        replacedert.notNull(jobDetail, "jobDetail can not be null");
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        scheduler.addJob(jobDetail, replace);
    }

    /**
     * 添加job
     * @param schedulerName
     * @param jobDetail
     * @return
     * @throws SchedulerException
     */
    public void addJob(String schedulerName, JobDetail jobDetail) throws SchedulerException {
        this.addJob(schedulerName, jobDetail, false);
    }

    public void updateJob(String schedulerName, JobDetail jobDetail) throws SchedulerException {
        if (existJob(schedulerName, jobDetail.getKey().getName(), jobDetail.getKey().getGroup())) {
            // 替换
            this.addJob(schedulerName, jobDetail, true);
        } else {
            throw new IllegalArgumentException("job [" + jobDetail.getKey().getName() + ":" + jobDetail.getKey().getGroup() + "] not exist");
        }
    }

    public JobDetail addMethodInovkeJob(String schedulerName, String jobName, String jobGroup, String description, MethodInvoker methodInvoker) throws SchedulerException {
        replacedert.notNull(methodInvoker, "methodInvoker can not be null");
        replacedert.notEmpty(schedulerName, "schedulerName can not be empty");
        replacedert.notEmpty(jobName, "jobName can not be empty");
        replacedert.notEmpty(jobGroup, "jobGroup can not be empty");
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("methodInvoker", methodInvoker);
        JobDetail jobDetail = JobBuilder.newJob(MethodInvokeJob.clreplaced).withIdenreplacedy(jobName, jobGroup).withDescription(description).setJobData(jobDataMap).storeDurably().build();
        addJob(schedulerName, jobDetail);
        return jobDetail;
    }

    public JobDetail updateMethodInovkeJob(String schedulerName, String jobName, String jobGroup, String description, MethodInvoker methodInvoker) throws SchedulerException {
        replacedert.notNull(methodInvoker, "methodInvoker can not be null");
        replacedert.notEmpty(schedulerName, "schedulerName can not be empty");
        replacedert.notEmpty(jobName, "jobName can not be empty");
        replacedert.notEmpty(jobGroup, "jobGroup can not be empty");
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("methodInvoker", methodInvoker);
        JobDetail jobDetail = JobBuilder.newJob(MethodInvokeJob.clreplaced).withIdenreplacedy(jobName, jobGroup).withDescription(description).setJobData(jobDataMap).storeDurably().build();
        updateJob(schedulerName, jobDetail);
        return jobDetail;
    }

    public JobDetail addMethodInovkeJob(String schedulerName, String jobName, String jobGroup, String jobClreplaced, Object[] constructorArguments, String jobClreplacedMethodName, Object[] jobClreplacedMethodArgs, String description) throws SchedulerException {
        replacedert.notNull(jobClreplaced, "jobClreplaced can not be null");
        replacedert.notEmpty(schedulerName, "schedulerName can not be empty");
        replacedert.notEmpty(jobName, "jobName can not be empty");
        replacedert.notEmpty(jobGroup, "jobGroup can not be empty");
        replacedert.notEmpty(jobClreplacedMethodName, "jobClreplacedMethodName can not be empty");
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("jobClreplaced", jobClreplaced);
        jobDataMap.put("constructorArguments", constructorArguments);
        jobDataMap.put("jobClreplacedMethodName", jobClreplacedMethodName);
        jobDataMap.put("jobClreplacedMethodArgs", jobClreplacedMethodArgs);
        JobDetail jobDetail = JobBuilder.newJob(MethodInvokeJob.clreplaced).withIdenreplacedy(jobName, jobGroup).withDescription(description).setJobData(jobDataMap).storeDurably().build();
        addJob(schedulerName, jobDetail);
        return jobDetail;
    }

    public JobDetail updateMethodInovkeJob(String schedulerName, String jobName, String jobGroup, String jobClreplaced, Object[] constructorArguments, String jobClreplacedMethodName, Object[] jobClreplacedMethodArgs, String description) throws SchedulerException {
        replacedert.notNull(jobClreplaced, "jobClreplaced can not be null");
        replacedert.notEmpty(schedulerName, "schedulerName can not be empty");
        replacedert.notEmpty(jobName, "jobName can not be empty");
        replacedert.notEmpty(jobGroup, "jobGroup can not be empty");
        replacedert.notEmpty(jobClreplacedMethodName, "jobClreplacedMethodName can not be empty");
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("jobClreplaced", jobClreplaced);
        jobDataMap.put("constructorArguments", constructorArguments);
        jobDataMap.put("jobClreplacedMethodName", jobClreplacedMethodName);
        jobDataMap.put("jobClreplacedMethodArgs", jobClreplacedMethodArgs);
        JobDetail jobDetail = JobBuilder.newJob(MethodInvokeJob.clreplaced).withIdenreplacedy(jobName, jobGroup).withDescription(description).setJobData(jobDataMap).storeDurably().build();
        updateJob(schedulerName, jobDetail);
        return jobDetail;
    }

    public JobDetail addStatefulMethodJob(String schedulerName, String jobName, String jobGroup, String description, MethodInvoker methodInvoker) throws SchedulerException {
        replacedert.notNull(methodInvoker, "methodInvoker can not be null");
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("methodInvoker", methodInvoker);
        JobDetail jobDetail = JobBuilder.newJob(StatefulMethodInvokeJob.clreplaced).withIdenreplacedy(jobName, jobGroup).withDescription(description).setJobData(jobDataMap).storeDurably().build();
        addJob(schedulerName, jobDetail);
        return jobDetail;
    }

    public JobDetail updateStatefulMethodJob(String schedulerName, String jobName, String jobGroup, String description, MethodInvoker methodInvoker) throws SchedulerException {
        replacedert.notNull(methodInvoker, "methodInvoker can not be null");
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("methodInvoker", methodInvoker);
        JobDetail jobDetail = JobBuilder.newJob(StatefulMethodInvokeJob.clreplaced).withIdenreplacedy(jobName, jobGroup).withDescription(description).setJobData(jobDataMap).storeDurably().build();
        updateJob(schedulerName, jobDetail);
        return jobDetail;
    }

    public JobDetail addStatefulMethodJob(String schedulerName, String jobName, String jobGroup, String jobClreplaced, Object[] constructorArguments, String jobClreplacedMethodName, Object[] jobClreplacedMethodArgs, String description) throws SchedulerException {
        replacedert.notNull(jobClreplaced, "jobClreplaced can not be null");
        replacedert.notEmpty(schedulerName, "schedulerName can not be empty");
        replacedert.notEmpty(jobName, "jobName can not be empty");
        replacedert.notEmpty(jobGroup, "jobGroup can not be empty");
        replacedert.notEmpty(jobClreplacedMethodName, "jobClreplacedMethodName can not be empty");
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("jobClreplaced", jobClreplaced);
        jobDataMap.put("constructorArguments", constructorArguments);
        jobDataMap.put("jobClreplacedMethodName", jobClreplacedMethodName);
        jobDataMap.put("jobClreplacedMethodArgs", jobClreplacedMethodArgs);
        JobDetail jobDetail = JobBuilder.newJob(StatefulMethodInvokeJob.clreplaced).withIdenreplacedy(jobName, jobGroup).withDescription(description).setJobData(jobDataMap).storeDurably().build();
        addJob(schedulerName, jobDetail);
        return jobDetail;
    }

    public JobDetail updateStatefulMethodJob(String schedulerName, String jobName, String jobGroup, String jobClreplaced, Object[] constructorArguments, String jobClreplacedMethodName, Object[] jobClreplacedMethodArgs, String description) throws SchedulerException {
        replacedert.notNull(jobClreplaced, "jobClreplaced can not be null");
        replacedert.notEmpty(schedulerName, "schedulerName can not be empty");
        replacedert.notEmpty(jobName, "jobName can not be empty");
        replacedert.notEmpty(jobGroup, "jobGroup can not be empty");
        replacedert.notEmpty(jobClreplacedMethodName, "jobClreplacedMethodName can not be empty");
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("jobClreplaced", jobClreplaced);
        jobDataMap.put("constructorArguments", constructorArguments);
        jobDataMap.put("jobClreplacedMethodName", jobClreplacedMethodName);
        jobDataMap.put("jobClreplacedMethodArgs", jobClreplacedMethodArgs);
        JobDetail jobDetail = JobBuilder.newJob(StatefulMethodInvokeJob.clreplaced).withIdenreplacedy(jobName, jobGroup).withDescription(description).setJobData(jobDataMap).storeDurably().build();
        updateJob(schedulerName, jobDetail);
        return jobDetail;
    }

    public void addTriggerForJob(String schedulerName, String jobName, String jobGroup, Trigger trigger) throws SchedulerException {
        JobDetail jobDetail = this.getJob(schedulerName, jobName, jobGroup);
        addTriggerForJob(schedulerName, jobDetail, trigger);
    }

    public void addTriggerForJob(String schedulerName, JobDetail jobDetail, Trigger trigger) throws SchedulerException {
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        scheduler.scheduleJob(jobDetail, trigger);
    }

    public void addTriggerForJob(String schedulerName, Trigger trigger) throws SchedulerException {
        replacedert.notNull(trigger, "trigger can not be null");
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        scheduler.scheduleJob(trigger);
    }

    /**
     * 更新Trigger
     * @param schedulerName
     * @param trigger
     * @throws SchedulerException
     */
    public void updateTriggerForJob(String schedulerName, Trigger trigger) throws SchedulerException {
        replacedert.notNull(trigger, "trigger can not be null");
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        if (existTrigger(schedulerName, QuartzUtils.getTriggerName(trigger), QuartzUtils.getTriggerGroup(trigger))) {
            scheduler.rescheduleJob(trigger.getKey(), trigger);
        } else {
            throw new IllegalArgumentException("trigger [" + trigger.getKey().getName() + ":" + trigger.getKey().getGroup() + "] not exist");
        }
    }

    public void pauseJob(String schedulerName, String jobName, String jobGroup) throws SchedulerException {
        replacedert.notEmpty(jobName, "jobName can not be empty");
        replacedert.notEmpty(jobGroup, "jobGroup can not be empty");
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        if (!existJob(schedulerName, jobName, jobGroup)) {
            throw new IllegalArgumentException("job [" + jobName + ":" + jobGroup + "] not exist");
        }
        QuartzUtils.pauseJob(jobName, jobGroup, scheduler);
    }

    public void resumeJob(String schedulerName, String jobName, String jobGroup) throws SchedulerException {
        replacedert.notEmpty(jobName, "jobName can not be empty");
        replacedert.notEmpty(jobGroup, "jobGroup can not be empty");
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        if (!existJob(schedulerName, jobName, jobGroup)) {
            throw new IllegalArgumentException("job [" + jobName + ":" + jobGroup + "] not exist");
        }
        QuartzUtils.resumeJob(jobName, jobGroup, scheduler);
    }

    public void removeJob(String schedulerName, String jobName, String jobGroup) throws SchedulerException {
        replacedert.notEmpty(jobName, "jobName can not be empty");
        replacedert.notEmpty(jobGroup, "jobGroup can not be empty");
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        if (!existJob(schedulerName, jobName, jobGroup)) {
            throw new IllegalArgumentException("job [" + jobName + ":" + jobGroup + "] not exist");
        }
        // 暂停
        QuartzUtils.pauseJob(jobName, jobGroup, scheduler);
        // 移除
        QuartzUtils.removeJob(jobName, jobGroup, scheduler);
    }

    /**
     * 运行job
     * @param schedulerName
     * @param jobName
     * @param jobGroup
     * @throws SchedulerException
     */
    public void runJob(String schedulerName, String jobName, String jobGroup) throws SchedulerException {
        replacedert.notEmpty(jobName, "jobName can not be empty");
        replacedert.notEmpty(jobGroup, "jobGroup can not be empty");
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        if (!existJob(schedulerName, jobName, jobGroup)) {
            throw new IllegalArgumentException("job [" + jobName + ":" + jobGroup + "] not exist");
        }
        JobDetail jobDetail = this.getJob(schedulerName, jobName, jobGroup);
        List<? extends Trigger> triggersOfJob = this.getTriggersOfJob(schedulerName, jobName, jobGroup);
        Set<Trigger> triggersSet = new HashSet<Trigger>();
        for (Trigger trigger : triggersOfJob) {
            triggersSet.add(trigger);
        }
        scheduler.scheduleJob(jobDetail, triggersSet, true);
    }

    public Trigger.TriggerState getTriggerState(String schedulerName, Trigger trigger) throws SchedulerException {
        replacedert.notNull(trigger, "trigger can not be null");
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        return QuartzUtils.getTriggerState(trigger, scheduler);
    }

    public void pauseTrigger(String schedulerName, String triggerName, String triggerGroup) throws SchedulerException {
        replacedert.notEmpty(triggerName, "triggerName can not be empty");
        replacedert.notEmpty(triggerGroup, "triggerGroup can not be empty");
        if (!existTrigger(schedulerName, triggerName, triggerGroup)) {
            throw new IllegalArgumentException("trigger [" + triggerName + ":" + triggerGroup + "] not exist");
        }
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        QuartzUtils.pauseTrigger(triggerName, triggerGroup, scheduler);
    }

    public void resumeTrigger(String schedulerName, String triggerName, String triggerGroup) throws SchedulerException {
        replacedert.notEmpty(triggerName, "triggerName can not be empty");
        replacedert.notEmpty(triggerGroup, "triggerGroup can not be empty");
        if (!existTrigger(schedulerName, triggerName, triggerGroup)) {
            throw new IllegalArgumentException("trigger [" + triggerName + ":" + triggerGroup + "] not exist");
        }
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        QuartzUtils.resumeTrigger(triggerName, triggerGroup, scheduler);
    }

    public void removeTrigger(String schedulerName, String triggerName, String triggerGroup) throws SchedulerException {
        replacedert.notEmpty(triggerName, "triggerName can not be empty");
        replacedert.notEmpty(triggerGroup, "triggerGroup can not be empty");
        if (!existTrigger(schedulerName, triggerName, triggerGroup)) {
            throw new IllegalArgumentException("trigger [" + triggerName + ":" + triggerGroup + "] not exist");
        }
        Scheduler scheduler = this.getreplacedertScheduler(schedulerName);
        QuartzUtils.removeTrigger(triggerName, triggerGroup, scheduler);
    }
}

18 View Complete Implementation : QuartzScheduler.java
Copyright Apache License 2.0
Author : snakerflow
/**
 * quartz框架实现的调度实例
 * @author yuqs
 * @since 1.4
 */
public clreplaced QuartzScheduler implements IScheduler {

    private static final Logger log = LoggerFactory.getLogger(QuartzScheduler.clreplaced);

    private SchedulerFactory schedulerFactory = new StdSchedulerFactory();

    private boolean isUseCalendar = false;

    private Scheduler getScheduler() {
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();
            String useCalendarStr = ConfigHelper.getProperty(CONFIG_USECALENDAR);
            boolean isUse = Boolean.parseBoolean(useCalendarStr);
            if (isUse) {
                BaseCalendar cal = null;
                try {
                    cal = build();
                } catch (Exception e) {
                    log.error("构造BaseCalendar失败->" + e.getMessage());
                }
                if (cal != null) {
                    scheduler.addCalendar(CALENDAR_NAME, cal, false, false);
                    isUseCalendar = true;
                }
            }
            scheduler.start();
            return scheduler;
        } catch (SchedulerException e) {
            throw new SnakerException(e);
        }
    }

    /**
     * 根据job实体调度具体的任务
     */
    public void schedule(JobEnreplacedy enreplacedy) {
        replacedertHelper.notNull(enreplacedy);
        JobDataMap data = new JobDataMap(enreplacedy.getArgs());
        data.put(KEY, enreplacedy.getId());
        data.put(MODEL, enreplacedy.getModelName());
        Clreplaced<? extends Job> jobClazz = null;
        String jobId = "";
        switch(enreplacedy.getJobType()) {
            case 0:
                jobClazz = ExecutorJob.clreplaced;
                jobId = TYPE_EXECUTOR + enreplacedy.getTask().getId();
                break;
            case 1:
                jobClazz = ReminderJob.clreplaced;
                jobId = TYPE_REMINDER + enreplacedy.getTask().getId();
                break;
        }
        if (jobClazz == null) {
            log.error("Quartz不支持的JOB类型:{}", enreplacedy.getJobType());
            return;
        }
        JobDetail job = JobBuilder.newJob(jobClazz).usingJobData(data).withIdenreplacedy(jobId, GROUP).build();
        Trigger trigger = null;
        TriggerBuilder<Trigger> builder = TriggerBuilder.newTrigger().withIdenreplacedy(StringHelper.getPrimaryKey(), GROUP).startAt(enreplacedy.getStartTime());
        if (jobClazz == ReminderJob.clreplaced && enreplacedy.getPeriod() > 0) {
            int count = ConfigHelper.getNumerProperty(CONFIG_REPEAT);
            if (count <= 0)
                count = 1;
            builder.withSchedule(SimpleScheduleBuilder.repeatMinutelyForTotalCount(count, enreplacedy.getPeriod()));
            if (isUseCalendar) {
                builder.modifiedByCalendar(CALENDAR_NAME);
            }
        }
        trigger = builder.build();
        try {
            log.info("jobId:{} clreplaced:{} starting......", jobId, jobClazz);
            getScheduler().scheduleJob(job, trigger);
        } catch (SchedulerException e) {
            log.error(e.getMessage());
        }
    }

    public void delete(String key) {
        replacedertHelper.notEmpty(key);
        try {
            log.info("jobId:{} deleted......", key);
            getScheduler().deleteJob(new JobKey(key, GROUP));
        } catch (SchedulerException e) {
            log.error(e.getMessage());
        }
    }

    private BaseCalendar build() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String holidays = ConfigHelper.getProperty(CONFIG_HOLIDAYS);
        String weeks = ConfigHelper.getProperty(CONFIG_WEEKS);
        String workTime = ConfigHelper.getProperty(CONFIG_WORKTIME);
        AnnualCalendar holidayCal = null;
        if (StringHelper.isNotEmpty(holidays)) {
            String[] holidayArray = holidays.split(",");
            ArrayList<Calendar> calendars = new ArrayList<Calendar>();
            try {
                for (String holiday : holidayArray) {
                    Date date = sdf.parse(holiday);
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(date);
                    calendars.add(new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)));
                }
            } catch (Exception e) {
                log.warn("节假日配置格式有误,请确认是否满足2013-01-04格式");
            }
            if (calendars.size() > 0) {
                holidayCal = new AnnualCalendar();
                holidayCal.setDaysExcluded(calendars);
            }
        }
        WeeklyCalendar weekdayCal = null;
        if (StringHelper.isNotEmpty(weeks)) {
            weekdayCal = new WeeklyCalendar(holidayCal);
            String[] weekArray = weeks.split(",");
            for (String week : weekArray) {
                if (NumberUtils.isNumber(week)) {
                    int w = Integer.parseInt(week);
                    weekdayCal.setDayExcluded(w + 1, true);
                } else {
                    log.warn("{} 不是合法的星期数值,请检查星期的配置在1~7内");
                }
            }
        }
        DailyCalendar dailyCal = null;
        if (StringHelper.isNotEmpty(workTime)) {
            String[] workTimeArray = workTime.split("-");
            if (workTimeArray.length == 2) {
                dailyCal = new DailyCalendar(weekdayCal == null ? holidayCal : weekdayCal, workTimeArray[0], workTimeArray[1]);
            }
        }
        return dailyCal == null ? (weekdayCal == null ? holidayCal : weekdayCal) : dailyCal;
    }
}

18 View Complete Implementation : SchedulerKernel.java
Copyright GNU General Public License v2.0
Author : spacewalkproject
/**
 * Taskomatic Kernel.
 */
public clreplaced SchedulerKernel {

    private static final String[] TASKOMATIC_PACKAGE_NAMES = { "com.redhat.rhn.taskomatic" };

    private static Logger log = Logger.getLogger(SchedulerKernel.clreplaced);

    private byte[] shutdownLock = new byte[0];

    private static SchedulerFactory factory = null;

    private static Scheduler scheduler = null;

    private static TaskoXmlRpcServer xmlrpcServer = null;

    private ChainedListener chainedTriggerListener = null;

    private String dataSourceConfigPath = "org.quartz.jobStore.dataSource";

    private String dataSourcePrefix = "org.quartz.dataSource";

    private String defaultDataSource = "rhnDs";

    /**
     * Kernel main driver behind Taskomatic
     * @throws InstantiationException thrown if this.scheduler can't be initialized.
     * @throws UnknownHostException thrown if xmlrcp host is unknown
     */
    public SchedulerKernel() throws InstantiationException, UnknownHostException {
        Properties props = Config.get().getNamespaceProperties("org.quartz");
        String dbUser = Config.get().getString(ConfigDefaults.DB_USER);
        String dbPreplaced = Config.get().getString(ConfigDefaults.DB_PreplacedWORD);
        props.setProperty(dataSourceConfigPath, defaultDataSource);
        String ds = dataSourcePrefix + "." + defaultDataSource;
        props.setProperty(ds + ".user", dbUser);
        props.setProperty(ds + ".preplacedword", dbPreplaced);
        // props.setProperty(ds + ".maxConnections", 30);
        if (ConfigDefaults.get().isOracle()) {
            props.setProperty("org.quartz.jobStore.driverDelegateClreplaced", "org.quartz.impl.jdbcjobstore.oracle.OracleDelegate");
            String driver = Config.get().getString(ConfigDefaults.DB_CLreplaced, "oracle.jdbc.driver.OracleDriver");
            props.setProperty(ds + ".driver", driver);
            props.setProperty(ds + ".URL", ConfigDefaults.get().getJdbcConnectionString());
        } else if (ConfigDefaults.get().isPostgresql()) {
            props.setProperty("org.quartz.jobStore.driverDelegateClreplaced", "org.quartz.impl.jdbcjobstore.PostgreSQLDelegate");
            String driver = Config.get().getString(ConfigDefaults.DB_CLreplaced, "org.postgresql.Driver");
            props.setProperty(ds + ".driver", driver);
            props.setProperty(ds + ".URL", ConfigDefaults.get().getJdbcConnectionString());
        } else {
            // This code should never get called as Exception would get
            // thrown in getJdbcConnectionString.
            throw new InstantiationException("Unknown db backend set, expecting oracle or postgresql");
        }
        try {
            SchedulerKernel.factory = new StdSchedulerFactory(props);
            SchedulerKernel.scheduler = SchedulerKernel.factory.getScheduler();
            SchedulerKernel.scheduler.setJobFactory(new RhnJobFactory());
            // Setup TriggerListener chain
            this.chainedTriggerListener = new ChainedListener();
            this.chainedTriggerListener.addListener(new TaskEnvironmentListener());
            try {
                SchedulerKernel.scheduler.addTriggerListener(this.chainedTriggerListener);
            } catch (SchedulerException e) {
                throw new ConfigException(e.getLocalizedMessage(), e);
            }
            xmlrpcServer = new TaskoXmlRpcServer(Config.get());
            xmlrpcServer.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
            throw new InstantiationException("this.scheduler failed");
        }
    }

    /**
     * returns scheduler
     * @return scheduler
     */
    public static Scheduler getScheduler() {
        return SchedulerKernel.scheduler;
    }

    /**
     * Starts Taskomatic
     * This method does not return until the this.scheduler is shutdown
     * @throws TaskomaticException error occurred during Quartz or Hibernate startup
     */
    public void startup() throws TaskomaticException {
        HibernateFactory.createSessionFactory(TASKOMATIC_PACKAGE_NAMES);
        if (!HibernateFactory.isInitialized()) {
            throw new TaskomaticException("HibernateFactory failed to initialize");
        }
        MessageQueue.startMessaging();
        MessageQueue.configureDefaultActions();
        try {
            SchedulerKernel.scheduler.start();
            initializeAllSatSchedules();
            synchronized (this.shutdownLock) {
                try {
                    this.shutdownLock.wait();
                } catch (InterruptedException ignored) {
                    return;
                }
            }
        } catch (SchedulerException e) {
            throw new TaskomaticException(e.getMessage(), e);
        }
    }

    /**
     * Initiates the shutdown process. Needs to happen in a
     * separate thread to prevent Quartz scheduler errors.
     */
    public void startShutdown() {
        Runnable shutdownTask = new Runnable() {

            public void run() {
                shutdown();
            }
        };
        Thread t = new Thread(shutdownTask);
        t.setDaemon(true);
        t.start();
    }

    /**
     * Shutsdown the application
     */
    protected void shutdown() {
        try {
            SchedulerKernel.scheduler.standby();
            SchedulerKernel.scheduler.shutdown();
        } catch (SchedulerException e) {
            // TODO Figure out what to do with this guy
            e.printStackTrace();
        } finally {
            MessageQueue.stopMessaging();
            HibernateFactory.closeSessionFactory();
            // Wake up thread waiting in startup() so it can exit
            synchronized (this.shutdownLock) {
                this.shutdownLock.notify();
            }
        }
    }

    /**
     * load DB schedule configuration
     */
    public void initializeAllSatSchedules() {
        List jobNames;
        Date now = new Date();
        try {
            jobNames = Arrays.asList(SchedulerKernel.scheduler.getJobNames(TaskoQuartzHelper.getGroupName(null)));
            for (TaskoSchedule schedule : TaskoFactory.listActiveSchedulesByOrg(null)) {
                if (!jobNames.contains(schedule.getJobLabel())) {
                    schedule.sanityCheckForPredefinedSchedules();
                    log.info("Initializing " + schedule.getJobLabel());
                    TaskoQuartzHelper.createJob(schedule);
                } else {
                    List<TaskoRun> runList = TaskoFactory.listNewerRunsBySchedule(schedule.getId(), now);
                    if (!runList.isEmpty()) {
                        // there're runs in the future
                        // reinit the schedule
                        Transaction tx = TaskoFactory.getSession().beginTransaction();
                        log.warn("Reinitializing " + schedule.getJobLabel() + ", found " + runList.size() + " runs in the future.");
                        TaskoFactory.reinitializeScheduleFromNow(schedule, now);
                        for (TaskoRun run : runList) {
                            TaskoFactory.deleteRun(run);
                        }
                        tx.commit();
                    }
                }
            }
            // delete outdated reposync leftovers
            TaskomaticApi tasko = new TaskomaticApi();
            for (Org org : OrgFactory.lookupAllOrgs()) {
                int removed = tasko.unscheduleInvalidRepoSyncSchedules(org);
                if (removed > 0) {
                    log.warn("" + removed + " outdated repo-sync schedules detected and " + "removed within org " + org.getId());
                }
            }
            // close unfinished runs
            int interrupted = 0;
            for (TaskoRun run : TaskoFactory.listUnfinishedRuns()) {
                run.setStatus(TaskoRun.STATUS_INTERRUPTED);
                run.setEndTime(now);
                TaskoFactory.save(run);
                interrupted++;
            }
            if (interrupted > 0) {
                log.warn("Number of interrupted runs: " + interrupted);
            }
            TaskoFactory.closeSession();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }
}

18 View Complete Implementation : TaskMgr.java
Copyright Apache License 2.0
Author : SwingFrog
public clreplaced TaskMgr {

    private static final Logger log = LoggerFactory.getLogger(TaskMgr.clreplaced);

    private SchedulerFactory schedulerFactory;

    private Scheduler scheduler;

    private static clreplaced SingleCase {

        public static final TaskMgr INSTANCE = new TaskMgr();
    }

    private TaskMgr() {
    }

    public static TaskMgr get() {
        return SingleCase.INSTANCE;
    }

    public void init(String fileName) throws SchedulerException {
        log.info("task init");
        schedulerFactory = new StdSchedulerFactory(fileName);
        scheduler = schedulerFactory.getScheduler();
    }

    public void startAll() throws SchedulerException {
        log.info("task start all");
        scheduler.start();
    }

    public void shutdownAll() throws SchedulerException {
        log.info("task shutdown all");
        scheduler.shutdown();
    }

    public void start(TaskTrigger taskTrigger) throws SchedulerException {
        scheduler.scheduleJob(taskTrigger.getJob(), taskTrigger.getTrigger());
    }

    public void stop(TaskTrigger taskTrigger) throws SchedulerException {
        scheduler.unscheduleJob(taskTrigger.getTrigger().getKey());
    }
}

18 View Complete Implementation : SchedulerKernel.java
Copyright GNU General Public License v2.0
Author : uyuni-project
/**
 * Taskomatic Kernel.
 */
public clreplaced SchedulerKernel {

    private static final String[] TASKOMATIC_PACKAGE_NAMES = { "com.redhat.rhn.taskomatic.domain" };

    private static Logger log = Logger.getLogger(SchedulerKernel.clreplaced);

    private byte[] shutdownLock = new byte[0];

    private static SchedulerFactory factory = null;

    private static Scheduler scheduler = null;

    private static TaskoXmlRpcServer xmlrpcServer = null;

    private ChainedListener chainedTriggerListener = null;

    private String dataSourceConfigPath = "org.quartz.jobStore.dataSource";

    private String dataSourcePrefix = "org.quartz.dataSource";

    private String defaultDataSource = "rhnDs";

    /**
     * Kernel main driver behind Taskomatic
     * @throws InstantiationException thrown if this.scheduler can't be initialized.
     * @throws UnknownHostException thrown if xmlrcp host is unknown
     */
    public SchedulerKernel() throws InstantiationException, UnknownHostException {
        Properties props = Config.get().getNamespaceProperties("org.quartz");
        String dbUser = Config.get().getString(ConfigDefaults.DB_USER);
        String dbPreplaced = Config.get().getString(ConfigDefaults.DB_PreplacedWORD);
        props.setProperty(dataSourceConfigPath, defaultDataSource);
        String ds = dataSourcePrefix + "." + defaultDataSource;
        props.setProperty(ds + ".user", dbUser);
        props.setProperty(ds + ".preplacedword", dbPreplaced);
        // props.setProperty(ds + ".maxConnections", 30);
        if (ConfigDefaults.get().isOracle()) {
            props.setProperty("org.quartz.jobStore.driverDelegateClreplaced", "org.quartz.impl.jdbcjobstore.oracle.OracleDelegate");
            String driver = Config.get().getString(ConfigDefaults.DB_CLreplaced, "oracle.jdbc.driver.OracleDriver");
            props.setProperty(ds + ".driver", driver);
            props.setProperty(ds + ".URL", ConfigDefaults.get().getJdbcConnectionString());
        } else if (ConfigDefaults.get().isPostgresql()) {
            props.setProperty("org.quartz.jobStore.driverDelegateClreplaced", "org.quartz.impl.jdbcjobstore.PostgreSQLDelegate");
            String driver = Config.get().getString(ConfigDefaults.DB_CLreplaced, "org.postgresql.Driver");
            props.setProperty(ds + ".driver", driver);
            props.setProperty(ds + ".URL", ConfigDefaults.get().getJdbcConnectionString());
        } else {
            // This code should never get called as Exception would get
            // thrown in getJdbcConnectionString.
            throw new InstantiationException("Unknown db backend set, expecting oracle or postgresql");
        }
        try {
            SchedulerKernel.factory = new StdSchedulerFactory(props);
            SchedulerKernel.scheduler = SchedulerKernel.factory.getScheduler();
            SchedulerKernel.scheduler.setJobFactory(new RhnJobFactory());
            // Setup TriggerListener chain
            this.chainedTriggerListener = new ChainedListener();
            this.chainedTriggerListener.addListener(new TaskEnvironmentListener());
            try {
                scheduler.getListenerManager().addTriggerListener(this.chainedTriggerListener);
            } catch (SchedulerException e) {
                throw new ConfigException(e.getLocalizedMessage(), e);
            }
            xmlrpcServer = new TaskoXmlRpcServer(Config.get());
            xmlrpcServer.start();
            PrometheusExporter.INSTANCE.startHttpServer();
            PrometheusExporter.INSTANCE.registerScheduler(SchedulerKernel.scheduler, "taskomatic");
        } catch (SchedulerException e) {
            e.printStackTrace();
            throw new InstantiationException("this.scheduler failed");
        }
    }

    /**
     * returns scheduler
     * @return scheduler
     */
    public static Scheduler getScheduler() {
        return SchedulerKernel.scheduler;
    }

    /**
     * Starts Taskomatic
     * This method does not return until the this.scheduler is shutdown
     * @throws TaskomaticException error occurred during Quartz or Hibernate startup
     */
    public void startup() throws TaskomaticException {
        HibernateFactory.createSessionFactory(TASKOMATIC_PACKAGE_NAMES);
        if (!HibernateFactory.isInitialized()) {
            throw new TaskomaticException("HibernateFactory failed to initialize");
        }
        MessageQueue.startMessaging();
        MessageQueue.configureDefaultActions();
        try {
            SchedulerKernel.scheduler.start();
            initializeAllSatSchedules();
            synchronized (this.shutdownLock) {
                try {
                    this.shutdownLock.wait();
                } catch (InterruptedException ignored) {
                    return;
                }
            }
        } catch (SchedulerException e) {
            throw new TaskomaticException(e.getMessage(), e);
        }
    }

    /**
     * Initiates the shutdown process. Needs to happen in a
     * separate thread to prevent Quartz scheduler errors.
     */
    public void startShutdown() {
        Runnable shutdownTask = new Runnable() {

            @Override
            public void run() {
                shutdown();
            }
        };
        Thread t = new Thread(shutdownTask);
        t.setDaemon(true);
        t.start();
    }

    /**
     * Shutsdown the application
     */
    protected void shutdown() {
        try {
            SchedulerKernel.scheduler.standby();
            SchedulerKernel.scheduler.shutdown();
        } catch (SchedulerException e) {
            // TODO Figure out what to do with this guy
            e.printStackTrace();
        } finally {
            MessageQueue.stopMessaging();
            HibernateFactory.closeSessionFactory();
            // Wake up thread waiting in startup() so it can exit
            synchronized (this.shutdownLock) {
                this.shutdownLock.notify();
            }
        }
    }

    /**
     * load DB schedule configuration
     */
    public void initializeAllSatSchedules() {
        Set<String> jobNames;
        Date now = new Date();
        try {
            jobNames = SchedulerKernel.scheduler.getJobKeys(GroupMatcher.anyJobGroup()).stream().map(jobKey -> jobKey.getName()).collect(toSet());
            for (TaskoSchedule schedule : TaskoFactory.listActiveSchedulesByOrg(null)) {
                if (!jobNames.contains(schedule.getJobLabel())) {
                    schedule.sanityCheckForPredefinedSchedules();
                    log.info("Initializing " + schedule.getJobLabel());
                    TaskoQuartzHelper.createJob(schedule);
                } else {
                    List<TaskoRun> runList = TaskoFactory.listNewerRunsBySchedule(schedule.getId(), now);
                    if (!runList.isEmpty()) {
                        // there're runs in the future
                        // reinit the schedule
                        log.warn("Reinitializing " + schedule.getJobLabel() + ", found " + runList.size() + " runs in the future.");
                        TaskoFactory.reinitializeScheduleFromNow(schedule, now);
                        for (TaskoRun run : runList) {
                            TaskoFactory.deleteRun(run);
                        }
                    }
                }
            }
            // delete outdated reposync leftovers
            TaskomaticApi tasko = new TaskomaticApi();
            for (Org org : OrgFactory.lookupAllOrgs()) {
                int removed = tasko.unscheduleInvalidRepoSyncSchedules(org);
                if (removed > 0) {
                    log.warn("" + removed + " outdated repo-sync schedules detected and " + "removed within org " + org.getId());
                }
            }
            // close unfinished runs
            int interrupted = 0;
            for (TaskoRun run : TaskoFactory.listUnfinishedRuns()) {
                run.setStatus(TaskoRun.STATUS_INTERRUPTED);
                run.setEndTime(now);
                TaskoFactory.save(run);
                interrupted++;
            }
            if (interrupted > 0) {
                log.warn("Number of interrupted runs: " + interrupted);
            }
            TaskoFactory.closeSession();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }
}

18 View Complete Implementation : TimerComponent.java
Copyright GNU General Public License v3.0
Author : xsonorg
public clreplaced TimerComponent implements TangYuanComponent {

    private static Log log = LogFactory.getLog(TimerComponent.clreplaced);

    private static String JOB_GROUP_NAME = "JOB_GROUP";

    private static String TRIGGER_GROUP_NAME = "TRIGGER_GROUP";

    private static TimerComponent instance = new TimerComponent();

    static {
        // timer 60 20
        TangYuanContainer.getInstance().registerComponent(new ComponentVo(instance, "timer", 60, 20));
    }

    private TimerComponent() {
    }

    public static TimerComponent getInstance() {
        return instance;
    }

    private SchedulerFactory schedulerfactory = null;

    private Scheduler scheduler = null;

    private List<TimerConfig> timerList = null;

    private void parse(String resource) throws Throwable {
        InputStream inputStream = Resources.getResourcereplacedtream(resource);
        XPathParser xPathParser = new XPathParser(inputStream);
        XmlNodeWrapper root = xPathParser.evalNode("/timer-component");
        List<XmlNodeWrapper> nodeList = root.evalNodes("timer");
        timerList = new ArrayList<TimerConfig>();
        for (XmlNodeWrapper node : nodeList) {
            String scheduled = StringUtils.trim(node.getStringAttribute("scheduled"));
            String service = StringUtils.trim(node.getStringAttribute("service"));
            String desc = StringUtils.trim(node.getStringAttribute("desc"));
            boolean sync = true;
            String _sync = StringUtils.trim(node.getStringAttribute("sync"));
            if (null != _sync) {
                sync = Boolean.parseBoolean(_sync);
            }
            CustomJob customJob = null;
            String custom = StringUtils.trim(node.getStringAttribute("custom"));
            if (null != custom) {
                Clreplaced<?> clazz = ClreplacedUtils.forName(custom);
                if (!CustomJob.clreplaced.isreplacedignableFrom(clazz)) {
                    throw new TangYuanException("User-defined JOB must implement org.xson.timer.client.CustomJob: " + custom);
                }
                // customJob = (CustomJob) clazz.newInstance();
                customJob = (CustomJob) TangYuanUtil.newInstance(clazz);
            }
            if (null == customJob && null == service) {
                throw new TangYuanException("job and service can not be empty");
            }
            TimerConfig config = new TimerConfig(scheduled, service, sync, false, desc, customJob);
            timerList.add(config);
        }
    }

    private void register() throws Throwable {
        for (int i = 0; i < timerList.size(); i++) {
            TimerConfig config = timerList.get(i);
            Clreplaced<? extends Job> jobClreplaced = config.isSync() ? NonConcurrentJob.clreplaced : ConcurrentJob.clreplaced;
            JobDetail job = JobBuilder.newJob(jobClreplaced).withIdenreplacedy("JOB" + i, JOB_GROUP_NAME).build();
            job.getJobDataMap().put("CONFIG", config);
            Trigger trigger = TriggerBuilder.newTrigger().withIdenreplacedy("TRIGGER" + i, TRIGGER_GROUP_NAME).withSchedule(CronScheduleBuilder.cronSchedule(config.getScheduled())).startNow().build();
            scheduler.scheduleJob(job, trigger);
            log.info("add timer: " + config.getService());
        }
    }

    @Override
    public void config(Map<String, String> properties) {
    }

    @Override
    public void start(String resource) throws Throwable {
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        log.info("timer client component starting, version: " + Version.getVersion());
        log.info("*** Start parsing: " + resource);
        // "config.xml"
        parse(resource);
        schedulerfactory = new StdSchedulerFactory();
        scheduler = schedulerfactory.getScheduler();
        register();
        scheduler.start();
        log.info("timer client component successfully.");
    }

    @Override
    public void stop(boolean wait) {
        try {
            log.info("timer client component stopping...");
            if (null != scheduler) {
                scheduler.shutdown();
            // scheduler.shutdown(wait);
            }
            log.info("timer client component stop successfully.");
        } catch (Throwable e) {
            log.error("timer client component stop error", e);
        }
    }
    // private String checkServiceUrl(String service) {
    // String url = service.toLowerCase().substring("http://".length());
    // String[] array = url.split("/");
    // // System.out.println(url);
    // if (3 == array.length) {
    // return service + "/@/Timer";
    // } else if (4 == array.length) {
    // return service + "/Timer";
    // } else if (5 == array.length) {
    // return service;
    // }
    // throw new TangYuanException("Illegal service format: " + service);
    // }
}

18 View Complete Implementation : QuartzManager.java
Copyright GNU General Public License v2.0
Author : zer0Black
/**
 * Quatrz调度框架的管理类,用于添加,删除,重置任务
 *
 * @author zer0
 * @version 1.0
 * @date 2015-11-30
 */
public clreplaced QuartzManager {

    private final static Logger Log = Logger.getLogger(QuartzManager.clreplaced);

    private static SchedulerFactory sf = new StdSchedulerFactory();

    /**
     * 添加调度任务
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param triggerGroupName
     * @param jobClreplaced
     * @param time
     * @param jobParam
     * @param count重复次数
     * @author zer0
     * @version 1.0
     * @date 2015-11-28
     */
    @SuppressWarnings("unchecked")
    public static void addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName, Clreplaced jobClreplaced, int time, int count, Map<String, Object> jobParam) {
        try {
            Scheduler sched = sf.getScheduler();
            // 任务名,任务组,任务执行类
            JobDetail job = newJob(jobClreplaced).withIdenreplacedy(jobName, jobGroupName).build();
            if (jobParam != null && jobParam.size() > 0) {
                // 给job添加参数
                job.getJobDataMap().putAll(jobParam);
            }
            // 触发器
            Trigger trigger = TriggerBuilder.newTrigger().withIdenreplacedy(triggerName, triggerGroupName).startAt(futureDate(time, IntervalUnit.SECOND)).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(time).withRepeatCount(count)).build();
            Date ft = sched.scheduleJob(job, trigger);
            Log.info(jobName + "启动于" + ft);
            // 启动
            if (!sched.isShutdown()) {
                sched.start();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除调度任务
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param triggerGroupName
     * @author zer0
     * @version 1.0
     * @date 2015-11-28
     */
    public static void removeJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName) {
        try {
            Scheduler sched = sf.getScheduler();
            TriggerKey triggerKey = new TriggerKey(triggerName, triggerGroupName);
            JobKey jobKey = new JobKey(jobName, jobGroupName);
            // 停止触发器
            sched.pauseTrigger(triggerKey);
            // 移除触发器
            sched.unscheduleJob(triggerKey);
            // 删除任务
            sched.deleteJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 重置调度任务
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param triggerGroupName
     * @author zer0
     * @version 1.0
     * @date 2015-12-3
     */
    public static void resetJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName, Clreplaced jobClreplaced, int time, int count, Map<String, Object> jobParam) {
        removeJob(jobName, jobGroupName, triggerName, triggerGroupName);
        addJob(jobName, jobGroupName, triggerName, triggerGroupName, jobClreplaced, time, count, jobParam);
    }
}

18 View Complete Implementation : Core.java
Copyright Apache License 2.0
Author : apache
public clreplaced Core implements IPendingServiceCallback, INetStreamEventHandler {

    private static final Logger log = getLogger(Core.clreplaced);

    private static final String STATUS_EXC = "Exception: ";

    private static final String METH_SHARE_ACTION = "screenSharerAction";

    static final String QUARTZ_GROUP_NAME = "ScreenShare";

    static final String QUARTZ_REMOTE_JOB_NAME = "RemoteJob";

    static final String QUARTZ_REMOTE_TRIGGER_NAME = "RemoteTrigger";

    private static final String CONNECT_REJECTED = "NetConnection.Connect.Rejected";

    private static final String CONNECT_FAILED = "NetConnection.Connect.Failed";

    enum Protocol {

        rtmp, rtmpt, rtmpe, rtmps
    }

    private IScreenShare instance = null;

    private URI url;

    private URI fallback;

    private boolean fallbackUsed = false;

    private String host;

    private String app;

    private int port;

    private String sid;

    private CaptureScreen _capture = null;

    private RTMPClientPublish publishClient = null;

    private ScreenSharerFrame frame;

    private int defaultQuality = 1;

    private int defaultFps = 10;

    private boolean showFps = true;

    private boolean allowRecording = true;

    private boolean allowPublishing = true;

    private boolean startSharing = false;

    private boolean startRecording = false;

    private boolean startPublishing = false;

    private boolean connected = false;

    private boolean readyToRecord = false;

    private boolean audioNotify = false;

    private boolean remoteEnabled = true;

    private boolean nativeSsl = false;

    private SchedulerFactory schdlrFactory;

    private Scheduler schdlr;

    private LinkedBlockingQueue<Map<String, Object>> remoteEvents = new LinkedBlockingQueue<>();

    private final ScreenDimensions dim;

    public Core(String[] args) {
        dim = new ScreenDimensions();
        try {
            System.setProperty("org.terracotta.quartz.skipUpdateCheck", "true");
            for (String arg : args) {
                log.debug("arg: {}", arg);
            }
            String[] textArray = null;
            if (args.length > 8) {
                url = new URI(args[0]);
                fallback = new URI(args[1]);
                sid = args[2];
                String labelTexts = args[3];
                defaultQuality = Integer.parseInt(args[4]);
                defaultFps = Integer.parseInt(args[5]);
                showFps = bool(args[6]);
                remoteEnabled = bool(args[7]);
                allowRecording = bool(args[8]);
                allowPublishing = bool(args[9]);
                nativeSsl = bool(args[10]);
                if (labelTexts.length() > 0) {
                    textArray = labelTexts.split(";");
                    if (log.isDebugEnabled()) {
                        log.debug("labelTexts :: {}", labelTexts);
                        log.debug("textArray Length {}", textArray.length);
                        for (int i = 0; i < textArray.length; i++) {
                            log.debug("{} :: {}", i, textArray[i]);
                        }
                    }
                }
            } else {
                System.exit(0);
            }
            schdlrFactory = new StdSchedulerFactory(getQurtzProps("CoreScreenShare"));
            schdlr = schdlrFactory.getScheduler();
            JobDetail remoteJob = JobBuilder.newJob(RemoteJob.clreplaced).withIdenreplacedy(QUARTZ_REMOTE_JOB_NAME, QUARTZ_GROUP_NAME).build();
            Trigger cursorTrigger = TriggerBuilder.newTrigger().withIdenreplacedy(QUARTZ_REMOTE_TRIGGER_NAME, QUARTZ_GROUP_NAME).withSchedule(simpleSchedule().withIntervalInMilliseconds(50).repeatForever()).build();
            remoteJob.getJobDataMap().put(RemoteJob.CORE_KEY, this);
            schdlr.scheduleJob(remoteJob, cursorTrigger);
            createWindow(textArray);
        } catch (Exception err) {
            log.error("", err);
        }
    }

    private CaptureScreen getCapture() {
        if (_capture == null) {
            _capture = new CaptureScreen(this, instance, host, app, port);
        }
        return _capture;
    }

    private void setInstance(URI uri) {
        Protocol protocol = Protocol.valueOf(uri.getScheme());
        host = uri.getHost();
        port = uri.getPort();
        app = uri.getPath().substring(1);
        switch(protocol) {
            case rtmp:
                instance = new RTMPScreenShare(this);
                break;
            case rtmpt:
                instance = new RTMPTScreenShare(this);
                break;
            case rtmps:
                if (nativeSsl) {
                    instance = new RTMPSScreenShare(this);
                } else {
                    instance = new RTMPTSScreenShare(this);
                }
                break;
            case rtmpe:
            default:
                throw new RuntimeException("Unsupported protocol");
        }
        instance.setServiceProvider(this);
        log.debug(String.format("host: %s, port: %s, app: %s, publish: %s", host, port, app, sid));
    }

    // ------------------------------------------------------------------------
    // 
    // Main
    // 
    // ------------------------------------------------------------------------
    public static void main(String[] args) {
        new Core(args);
    }

    // ------------------------------------------------------------------------
    // 
    // GUI
    // 
    // ------------------------------------------------------------------------
    public void createWindow(String[] textArray) {
        try {
            frame = new ScreenSharerFrame(this, textArray);
            frame.setVisible(true);
            frame.setRecordingTabEnabled(allowRecording);
            frame.setPublishingTabEnabled(allowPublishing);
            log.debug("initialized");
        } catch (Exception err) {
            log.error("createWindow Exception: ", err);
        }
    }

    public void sendCursorStatus() {
        try {
            Point mouseP = MouseInfo.getPointerInfo().getLocation();
            float scaleFactor = (1.0f * dim.getResizeX()) / dim.getSpinnerWidth();
            // Real size: Real mouse position = Resize : X
            int x = (int) ((mouseP.getX() - dim.getSpinnerX()) * scaleFactor);
            int y = (int) ((mouseP.getY() - dim.getSpinnerY()) * scaleFactor);
            if (instance.getConnection() != null) {
                if (Red5.getConnectionLocal() == null) {
                    Red5.setConnectionLocal(instance.getConnection());
                }
                instance.invoke("setNewCursorPosition", new Object[] { x, y }, this);
            }
        } catch (NullPointerException npe) {
        // noop
        } catch (Exception err) {
            frame.setStatus(STATUS_EXC + err);
            log.error("[sendCursorStatus]", err);
        }
    }

    /**
     * @param id The streamid sent by server
     */
    public void setId(String id) {
    // no-op
    }

    public void setConnectionreplacedharingClient() {
        log.debug("########## setConnectionreplacedharingClient");
        try {
            if (Red5.getConnectionLocal() == null) {
                Red5.setConnectionLocal(instance.getConnection());
            }
            Map<String, Object> map = new HashMap<>();
            int scaledWidth = dim.getResizeX();
            int scaledHeight = dim.getResizeY();
            map.put("screenWidth", scaledWidth);
            map.put("screenHeight", scaledHeight);
            map.put("startRecording", startRecording);
            map.put("startStreaming", startSharing);
            map.put("startPublishing", startPublishing);
            map.put("publishingHost", frame.getPublishHost());
            map.put("publishingApp", frame.getPublishApp());
            map.put("publishingId", frame.getPublishId());
            if (Red5.getConnectionLocal() == null) {
                Red5.setConnectionLocal(instance.getConnection());
            }
            instance.invoke("setConnectionreplacedharingClient", new Object[] { map }, this);
        } catch (Exception err) {
            frame.setStatus("Error: " + err.getLocalizedMessage());
            log.error("[setConnectionreplacedharingClient]", err);
        }
    }

    public void sharingStart() {
        try {
            schdlr.start();
        } catch (SchedulerException e) {
            log.error("[schdlr.start]", e);
        }
        startSharing = true;
        captureScreenStart();
    }

    public void recordingStart() {
        startRecording = true;
        captureScreenStart();
    }

    public void publishingStart() {
        startPublishing = true;
        captureScreenStart();
    }

    private void connect(String sid) {
        setInstance(fallbackUsed ? fallback : url);
        Map<String, Object> map = instance.makeDefaultConnectionParams(host, port, app);
        map.put("screenClient", true);
        Map<String, Object> params = new HashMap<>();
        params.put("sid", sid);
        instance.connect(host, port, map, this, new Object[] { params });
    }

    void handleException(Throwable e) {
        frame.setStatus(STATUS_EXC + e);
        if (e instanceof ConnectException) {
            fallbackUsed = true;
            connect(sid);
        }
    }

    private void captureScreenStart() {
        try {
            log.debug("captureScreenStart");
            if (!connected) {
                connect(sid);
            } else {
                setConnectionreplacedharingClient();
            }
        } catch (Exception err) {
            log.error("captureScreenStart Exception: ", err);
            frame.setStatus(STATUS_EXC + err);
        }
    }

    public void sharingStop() {
        startSharing = false;
        captureScreenStop("stopStreaming");
    }

    public void recordingStop() {
        startRecording = false;
        captureScreenStop("stopRecording");
    }

    public void publishingStop() {
        startPublishing = false;
        captureScreenStop("stopPublishing");
    }

    private void captureScreenStop(String action) {
        try {
            log.debug("INVOKE screenSharerAction");
            Map<String, Object> map = new HashMap<>();
            map.put(action, true);
            if (Red5.getConnectionLocal() == null) {
                Red5.setConnectionLocal(instance.getConnection());
            }
            instance.invoke(METH_SHARE_ACTION, new Object[] { map }, this);
        } catch (Exception err) {
            log.error("captureScreenStop Exception: ", err);
            frame.setStatus(STATUS_EXC + err);
        }
    }

    public void stopSharing() {
        try {
            schdlr.standby();
        } catch (SchedulerException e) {
            log.error("[schdlr.standby]", e);
        }
        frame.setSharingStatus(false, !startPublishing && !startRecording && !startSharing);
        startSharing = false;
    }

    public void stopRecording() {
        frame.setRecordingStatus(false, !startPublishing && !startRecording && !startSharing);
        startRecording = false;
    }

    public void stopPublishing() {
        frame.setPublishingStatus(false, !startPublishing && !startRecording && !startSharing);
        startPublishing = false;
        if (publishClient != null) {
            publishClient.disconnect();
            publishClient = null;
        }
    }

    public synchronized boolean isReadyToRecord() {
        return readyToRecord;
    }

    private synchronized void setReadyToRecord(boolean readyToRecord) {
        this.readyToRecord = readyToRecord;
    }

    /**
     * @param command - command to be processed
     */
    protected void onCommand(ICommand command) {
        if (!(command instanceof Notify)) {
            return;
        }
        Notify invoke = (Notify) command;
        if (invoke.getType() == IEvent.Type.STREAM_DATA) {
            return;
        }
        String method = invoke.getCall().getServiceMethodName();
        if (METH_SHARE_ACTION.equals(method)) {
            Object[] args = invoke.getCall().getArguments();
            if (args != null && args.length > 0) {
                @SuppressWarnings("unchecked")
                Map<String, Object> params = (Map<String, Object>) args[0];
                if (bool(params.get("stopPublishing"))) {
                    stopPublishing();
                }
                if (params.containsKey("error")) {
                    frame.setStatus("" + params.get("error"));
                }
            }
        }
    }

    /**
     * Will stop any activity and disconnect
     *
     * @param obj - dummy unused param to perform the call
     */
    public void stopStream(Object obj) {
        try {
            log.debug("ScreenShare stopStream");
            stopSharing();
            stopRecording();
            stopPublishing();
            connected = false;
            if (instance != null) {
                instance.disconnect();
            }
            setReadyToRecord(false);
            getCapture().setStartPublish(false);
            getCapture().release();
            _capture = null;
        } catch (Exception e) {
            log.error("ScreenShare stopStream exception ", e);
        }
    }

    @Override
    public void onStreamEvent(Notify notify) {
        log.debug("onStreamEvent {}", notify);
        @SuppressWarnings("rawtypes")
        ObjectMap map = (ObjectMap) notify.getCall().getArguments()[0];
        String code = (String) map.get("code");
        if (StatusCodes.NS_PUBLISH_START.equals(code)) {
            log.debug("onStreamEvent Publish start");
            getCapture().setStartPublish(true);
            setReadyToRecord(true);
        }
    }

    private static boolean bool(Object b) {
        return TRUE.equals(Boolean.valueOf("" + b));
    }

    public void sendRemoteCursorEvent(Map<String, Object> obj) {
        if (!remoteEnabled) {
            return;
        }
        log.trace("#### sendRemoteCursorEvent ");
        log.trace("Result Map Type {}", obj);
        if (obj != null) {
            remoteEvents.offer(obj);
            log.trace("Action offered:: {}, count: {}", obj, remoteEvents.size());
        }
    }

    @Override
    public void resultReceived(IPendingServiceCall call) {
        try {
            log.trace("service call result: {}", call);
            if (call == null) {
                return;
            }
            String method = call.getServiceMethodName();
            Object o = call.getResult();
            if (log.isTraceEnabled()) {
                log.trace("Result Map Type {}", (o == null ? null : o.getClreplaced().getName()));
                log.trace("{}", o);
            }
            @SuppressWarnings("unchecked")
            Map<String, Object> returnMap = (o != null && o instanceof Map) ? (Map<String, Object>) o : new HashMap<>();
            log.trace("call ### get Method Name {}", method);
            if ("connect".equals(method)) {
                Object code = returnMap.get("code");
                if (CONNECT_FAILED.equals(code) && !fallbackUsed) {
                    fallbackUsed = true;
                    connect(sid);
                    frame.setStatus("Re-connecting using fallback");
                    return;
                }
                if (CONNECT_FAILED.equals(code) || CONNECT_REJECTED.equals(code)) {
                    frame.setStatus(String.format("Error: %s %s", code, returnMap.get("description")));
                    return;
                }
                connected = true;
                setConnectionreplacedharingClient();
            } else if ("setConnectionreplacedharingClient".equals(method)) {
                if (!bool(returnMap.get("alreadyPublished"))) {
                    log.trace("Stream not yet started - do it ");
                    instance.createStream(this);
                } else {
                    log.trace("The Stream was already started ");
                }
                if (o != null) {
                    Object modus = returnMap.get("modus");
                    if ("startStreaming".equals(modus)) {
                        frame.setSharingStatus(true, false);
                    } else if ("startRecording".equals(modus)) {
                        frame.setRecordingStatus(true, false);
                    } else if ("startPublishing".equals(modus)) {
                        frame.setPublishingStatus(true, false);
                        publishClient = new RTMPClientPublish(this, frame.getPublishHost(), frame.getPublishApp(), frame.getPublishId());
                        publishClient.connect();
                    }
                } else {
                    String err = "Could not aquire modus for event setConnectionreplacedharingClient";
                    frame.setStatus(String.format("Error: %s", err));
                    return;
                }
            } else if ("createStream".equals(method)) {
                if (startRecording || startSharing) {
                    CaptureScreen capture = getCapture();
                    if (o != null && o instanceof Number) {
                        if (capture.getStreamId() != null) {
                            instance.unpublish(capture.getStreamId());
                        }
                        capture.setStreamId((Number) o);
                    }
                    final String broadcastId = randomUUID().toString();
                    log.debug("createPublishStream result stream id: {}; name: {}", capture.getStreamId(), broadcastId);
                    instance.publish(capture.getStreamId(), broadcastId, "live", this);
                    log.debug("setup capture thread spinnerWidth = {}; spinnerHeight = {};", dim.getSpinnerWidth(), dim.getSpinnerHeight());
                    if (!capture.isStarted()) {
                        capture.setSendCursor(startSharing);
                        capture.start();
                    }
                }
            } else if (METH_SHARE_ACTION.equals(method)) {
                Object result = returnMap.get("result");
                if ("stopAll".equals(result)) {
                    log.trace("Stopping to stream, there is neither a Desktop Sharing nor Recording anymore");
                    stopStream(null);
                } else if ("stopSharingOnly".equals(result)) {
                    stopSharing();
                } else if ("stopRecordingOnly".equals(result)) {
                    stopRecording();
                } else if ("stopPublishingOnly".equals(result)) {
                    stopPublishing();
                }
            } else if ("setNewCursorPosition".equals(method)) {
            // Do not do anything
            } else {
                log.debug("Unknown method {}", method);
            }
        } catch (Exception err) {
            log.error("[resultReceived]", err);
        }
    }

    public boolean isAudioNotify() {
        return audioNotify;
    }

    public void setAudioNotify(boolean audioNotify) {
        this.audioNotify = audioNotify;
    }

    public boolean isRemoteEnabled() {
        return remoteEnabled;
    }

    public void setRemoteEnabled(boolean remoteEnabled) {
        this.remoteEnabled = remoteEnabled;
    }

    public void setDeadlockGuard(RTMPConnection conn) {
        ThreadPoolTaskScheduler deadlockGuard = new ThreadPoolTaskScheduler();
        deadlockGuard.setPoolSize(16);
        deadlockGuard.setDaemon(false);
        deadlockGuard.setWaitForTasksToCompleteOnShutdown(true);
        deadlockGuard.setThreadNamePrefix("DeadlockGuardScheduler-");
        deadlockGuard.afterPropertiesSet();
        conn.setDeadlockGuardScheduler(deadlockGuard);
    }

    public IScreenShare getInstance() {
        return instance;
    }

    public LinkedBlockingQueue<Map<String, Object>> getRemoteEvents() {
        return remoteEvents;
    }

    public ScreenDimensions getDim() {
        return dim;
    }

    public int getDefaultQuality() {
        return defaultQuality;
    }

    public int getDefaultFps() {
        return defaultFps;
    }

    public boolean isShowFps() {
        return showFps;
    }
}

18 View Complete Implementation : SchedulerFactoryBean.java
Copyright MIT License
Author : codeEngraver
/**
 * {@link FactoryBean} that creates and configures a Quartz {@link org.quartz.Scheduler},
 * manages its lifecycle as part of the Spring application context, and exposes the
 * Scheduler as bean reference for dependency injection.
 *
 * <p>Allows registration of JobDetails, Calendars and Triggers, automatically
 * starting the scheduler on initialization and shutting it down on destruction.
 * In scenarios that just require static registration of jobs at startup, there
 * is no need to access the Scheduler instance itself in application code.
 *
 * <p>For dynamic registration of jobs at runtime, use a bean reference to
 * this SchedulerFactoryBean to get direct access to the Quartz Scheduler
 * ({@code org.quartz.Scheduler}). This allows you to create new jobs
 * and triggers, and also to control and monitor the entire Scheduler.
 *
 * <p>Note that Quartz instantiates a new Job for each execution, in
 * contrast to Timer which uses a TimerTask instance that is shared
 * between repeated executions. Just JobDetail descriptors are shared.
 *
 * <p>When using persistent jobs, it is strongly recommended to perform all
 * operations on the Scheduler within Spring-managed (or plain JTA) transactions.
 * Else, database locking will not properly work and might even break.
 * (See {@link #setDataSource setDataSource} javadoc for details.)
 *
 * <p>The preferred way to achieve transactional execution is to demarcate
 * declarative transactions at the business facade level, which will
 * automatically apply to Scheduler operations performed within those scopes.
 * Alternatively, you may add transactional advice for the Scheduler itself.
 *
 * <p>Compatible with Quartz 2.1.4 and higher, as of Spring 4.1.
 *
 * @author Juergen Hoeller
 * @since 18.02.2004
 * @see #setDataSource
 * @see org.quartz.Scheduler
 * @see org.quartz.SchedulerFactory
 * @see org.quartz.impl.StdSchedulerFactory
 * @see org.springframework.transaction.interceptor.TransactionProxyFactoryBean
 */
public clreplaced SchedulerFactoryBean extends SchedulerAccessor implements FactoryBean<Scheduler>, BeanNameAware, ApplicationContextAware, InitializingBean, DisposableBean, SmartLifecycle {

    /**
     * The thread count property.
     */
    public static final String PROP_THREAD_COUNT = "org.quartz.threadPool.threadCount";

    /**
     * The default thread count.
     */
    public static final int DEFAULT_THREAD_COUNT = 10;

    private static final ThreadLocal<ResourceLoader> configTimeResourceLoaderHolder = new ThreadLocal<>();

    private static final ThreadLocal<Executor> configTimeTaskExecutorHolder = new ThreadLocal<>();

    private static final ThreadLocal<DataSource> configTimeDataSourceHolder = new ThreadLocal<>();

    private static final ThreadLocal<DataSource> configTimeNonTransactionalDataSourceHolder = new ThreadLocal<>();

    /**
     * Return the {@link ResourceLoader} for the currently configured Quartz Scheduler,
     * to be used by {@link ResourceLoaderClreplacedLoadHelper}.
     * <p>This instance will be set before initialization of the corresponding Scheduler,
     * and reset immediately afterwards. It is thus only available during configuration.
     * @see #setApplicationContext
     * @see ResourceLoaderClreplacedLoadHelper
     */
    @Nullable
    public static ResourceLoader getConfigTimeResourceLoader() {
        return configTimeResourceLoaderHolder.get();
    }

    /**
     * Return the {@link Executor} for the currently configured Quartz Scheduler,
     * to be used by {@link LocalTaskExecutorThreadPool}.
     * <p>This instance will be set before initialization of the corresponding Scheduler,
     * and reset immediately afterwards. It is thus only available during configuration.
     * @since 2.0
     * @see #setTaskExecutor
     * @see LocalTaskExecutorThreadPool
     */
    @Nullable
    public static Executor getConfigTimeTaskExecutor() {
        return configTimeTaskExecutorHolder.get();
    }

    /**
     * Return the {@link DataSource} for the currently configured Quartz Scheduler,
     * to be used by {@link LocalDataSourceJobStore}.
     * <p>This instance will be set before initialization of the corresponding Scheduler,
     * and reset immediately afterwards. It is thus only available during configuration.
     * @since 1.1
     * @see #setDataSource
     * @see LocalDataSourceJobStore
     */
    @Nullable
    public static DataSource getConfigTimeDataSource() {
        return configTimeDataSourceHolder.get();
    }

    /**
     * Return the non-transactional {@link DataSource} for the currently configured
     * Quartz Scheduler, to be used by {@link LocalDataSourceJobStore}.
     * <p>This instance will be set before initialization of the corresponding Scheduler,
     * and reset immediately afterwards. It is thus only available during configuration.
     * @since 1.1
     * @see #setNonTransactionalDataSource
     * @see LocalDataSourceJobStore
     */
    @Nullable
    public static DataSource getConfigTimeNonTransactionalDataSource() {
        return configTimeNonTransactionalDataSourceHolder.get();
    }

    @Nullable
    private SchedulerFactory schedulerFactory;

    private Clreplaced<? extends SchedulerFactory> schedulerFactoryClreplaced = StdSchedulerFactory.clreplaced;

    @Nullable
    private String schedulerName;

    @Nullable
    private Resource configLocation;

    @Nullable
    private Properties quartzProperties;

    @Nullable
    private Executor taskExecutor;

    @Nullable
    private DataSource dataSource;

    @Nullable
    private DataSource nonTransactionalDataSource;

    @Nullable
    private Map<String, ?> schedulerContextMap;

    @Nullable
    private String applicationContextSchedulerContextKey;

    @Nullable
    private JobFactory jobFactory;

    private boolean jobFactorySet = false;

    private boolean autoStartup = true;

    private int startupDelay = 0;

    private int phase = DEFAULT_PHASE;

    private boolean exposeSchedulerInRepository = false;

    private boolean waitForJobsToCompleteOnShutdown = false;

    @Nullable
    private String beanName;

    @Nullable
    private ApplicationContext applicationContext;

    @Nullable
    private Scheduler scheduler;

    /**
     * Set an external Quartz {@link SchedulerFactory} instance to use.
     * <p>Default is an internal {@link StdSchedulerFactory} instance. If this method is
     * called, it overrides any clreplaced specified through {@link #setSchedulerFactoryClreplaced}
     * as well as any settings specified through {@link #setConfigLocation},
     * {@link #setQuartzProperties}, {@link #setTaskExecutor} or {@link #setDataSource}.
     * <p><b>NOTE:</b> With an externally provided {@code SchedulerFactory} instance,
     * local settings such as {@link #setConfigLocation} or {@link #setQuartzProperties}
     * will be ignored here in {@code SchedulerFactoryBean}, expecting the external
     * {@code SchedulerFactory} instance to get initialized on its own.
     * @since 4.3.15
     * @see #setSchedulerFactoryClreplaced
     */
    public void setSchedulerFactory(SchedulerFactory schedulerFactory) {
        this.schedulerFactory = schedulerFactory;
    }

    /**
     * Set the Quartz {@link SchedulerFactory} implementation to use.
     * <p>Default is the {@link StdSchedulerFactory} clreplaced, reading in the standard
     * {@code quartz.properties} from {@code quartz.jar}. For applying custom Quartz
     * properties, specify {@link #setConfigLocation "configLocation"} and/or
     * {@link #setQuartzProperties "quartzProperties"} etc on this local
     * {@code SchedulerFactoryBean} instance.
     * @see org.quartz.impl.StdSchedulerFactory
     * @see #setConfigLocation
     * @see #setQuartzProperties
     * @see #setTaskExecutor
     * @see #setDataSource
     */
    public void setSchedulerFactoryClreplaced(Clreplaced<? extends SchedulerFactory> schedulerFactoryClreplaced) {
        this.schedulerFactoryClreplaced = schedulerFactoryClreplaced;
    }

    /**
     * Set the name of the Scheduler to create via the SchedulerFactory, as an
     * alternative to the {@code org.quartz.scheduler.instanceName} property.
     * <p>If not specified, the name will be taken from Quartz properties
     * ({@code org.quartz.scheduler.instanceName}), or from the declared
     * {@code SchedulerFactoryBean} bean name as a fallback.
     * @see #setBeanName
     * @see StdSchedulerFactory#PROP_SCHED_INSTANCE_NAME
     * @see org.quartz.SchedulerFactory#getScheduler()
     * @see org.quartz.SchedulerFactory#getScheduler(String)
     */
    public void setSchedulerName(String schedulerName) {
        this.schedulerName = schedulerName;
    }

    /**
     * Set the location of the Quartz properties config file, for example
     * as clreplacedpath resource "clreplacedpath:quartz.properties".
     * <p>Note: Can be omitted when all necessary properties are specified
     * locally via this bean, or when relying on Quartz' default configuration.
     * @see #setQuartzProperties
     */
    public void setConfigLocation(Resource configLocation) {
        this.configLocation = configLocation;
    }

    /**
     * Set Quartz properties, like "org.quartz.threadPool.clreplaced".
     * <p>Can be used to override values in a Quartz properties config file,
     * or to specify all necessary properties locally.
     * @see #setConfigLocation
     */
    public void setQuartzProperties(Properties quartzProperties) {
        this.quartzProperties = quartzProperties;
    }

    /**
     * Set a Spring-managed {@link Executor} to use as Quartz backend.
     * Exposed as thread pool through the Quartz SPI.
     * <p>Can be used to replacedign a local JDK ThreadPoolExecutor or a CommonJ
     * WorkManager as Quartz backend, to avoid Quartz's manual thread creation.
     * <p>By default, a Quartz SimpleThreadPool will be used, configured through
     * the corresponding Quartz properties.
     * @since 2.0
     * @see #setQuartzProperties
     * @see LocalTaskExecutorThreadPool
     * @see org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
     * @see org.springframework.scheduling.concurrent.DefaultManagedTaskExecutor
     */
    public void setTaskExecutor(Executor taskExecutor) {
        this.taskExecutor = taskExecutor;
    }

    /**
     * Set the default {@link DataSource} to be used by the Scheduler.
     * If set, this will override corresponding settings in Quartz properties.
     * <p>Note: If this is set, the Quartz settings should not define
     * a job store "dataSource" to avoid meaningless double configuration.
     * <p>A Spring-specific subclreplaced of Quartz' JobStoreCMT will be used.
     * It is therefore strongly recommended to perform all operations on
     * the Scheduler within Spring-managed (or plain JTA) transactions.
     * Else, database locking will not properly work and might even break
     * (e.g. if trying to obtain a lock on Oracle without a transaction).
     * <p>Supports both transactional and non-transactional DataSource access.
     * With a non-XA DataSource and local Spring transactions, a single DataSource
     * argument is sufficient. In case of an XA DataSource and global JTA transactions,
     * SchedulerFactoryBean's "nonTransactionalDataSource" property should be set,
     * preplaceding in a non-XA DataSource that will not participate in global transactions.
     * @since 1.1
     * @see #setNonTransactionalDataSource
     * @see #setQuartzProperties
     * @see #setTransactionManager
     * @see LocalDataSourceJobStore
     */
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * Set the {@link DataSource} to be used <i>for non-transactional access</i>.
     * <p>This is only necessary if the default DataSource is an XA DataSource that will
     * always participate in transactions: A non-XA version of that DataSource should
     * be specified as "nonTransactionalDataSource" in such a scenario.
     * <p>This is not relevant with a local DataSource instance and Spring transactions.
     * Specifying a single default DataSource as "dataSource" is sufficient there.
     * @since 1.1
     * @see #setDataSource
     * @see LocalDataSourceJobStore
     */
    public void setNonTransactionalDataSource(DataSource nonTransactionalDataSource) {
        this.nonTransactionalDataSource = nonTransactionalDataSource;
    }

    /**
     * Register objects in the Scheduler context via a given Map.
     * These objects will be available to any Job that runs in this Scheduler.
     * <p>Note: When using persistent Jobs whose JobDetail will be kept in the
     * database, do not put Spring-managed beans or an ApplicationContext
     * reference into the JobDataMap but rather into the SchedulerContext.
     * @param schedulerContextAsMap a Map with String keys and any objects as
     * values (for example Spring-managed beans)
     * @see JobDetailFactoryBean#setJobDataAsMap
     */
    public void setSchedulerContextAsMap(Map<String, ?> schedulerContextAsMap) {
        this.schedulerContextMap = schedulerContextAsMap;
    }

    /**
     * Set the key of an {@link ApplicationContext} reference to expose in the
     * SchedulerContext, for example "applicationContext". Default is none.
     * Only applicable when running in a Spring ApplicationContext.
     * <p>Note: When using persistent Jobs whose JobDetail will be kept in the
     * database, do not put an ApplicationContext reference into the JobDataMap
     * but rather into the SchedulerContext.
     * <p>In case of a QuartzJobBean, the reference will be applied to the Job
     * instance as bean property. An "applicationContext" attribute will
     * correspond to a "setApplicationContext" method in that scenario.
     * <p>Note that BeanFactory callback interfaces like ApplicationContextAware
     * are not automatically applied to Quartz Job instances, because Quartz
     * itself is responsible for the lifecycle of its Jobs.
     * @see JobDetailFactoryBean#setApplicationContextJobDataKey
     * @see org.springframework.context.ApplicationContext
     */
    public void setApplicationContextSchedulerContextKey(String applicationContextSchedulerContextKey) {
        this.applicationContextSchedulerContextKey = applicationContextSchedulerContextKey;
    }

    /**
     * Set the Quartz {@link JobFactory} to use for this Scheduler.
     * <p>Default is Spring's {@link AdaptableJobFactory}, which supports
     * {@link java.lang.Runnable} objects as well as standard Quartz
     * {@link org.quartz.Job} instances. Note that this default only applies
     * to a <i>local</i> Scheduler, not to a RemoteScheduler (where setting
     * a custom JobFactory is not supported by Quartz).
     * <p>Specify an instance of Spring's {@link SpringBeanJobFactory} here
     * (typically as an inner bean definition) to automatically populate a job's
     * bean properties from the specified job data map and scheduler context.
     * @since 2.0
     * @see AdaptableJobFactory
     * @see SpringBeanJobFactory
     */
    public void setJobFactory(JobFactory jobFactory) {
        this.jobFactory = jobFactory;
        this.jobFactorySet = true;
    }

    /**
     * Set whether to automatically start the scheduler after initialization.
     * <p>Default is "true"; set this to "false" to allow for manual startup.
     */
    public void setAutoStartup(boolean autoStartup) {
        this.autoStartup = autoStartup;
    }

    /**
     * Return whether this scheduler is configured for auto-startup. If "true",
     * the scheduler will start after the context is refreshed and after the
     * start delay, if any.
     */
    @Override
    public boolean isAutoStartup() {
        return this.autoStartup;
    }

    /**
     * Specify the phase in which this scheduler should be started and stopped.
     * The startup order proceeds from lowest to highest, and the shutdown order
     * is the reverse of that. By default this value is {@code Integer.MAX_VALUE}
     * meaning that this scheduler starts as late as possible and stops as soon
     * as possible.
     * @since 3.0
     */
    public void setPhase(int phase) {
        this.phase = phase;
    }

    /**
     * Return the phase in which this scheduler will be started and stopped.
     */
    @Override
    public int getPhase() {
        return this.phase;
    }

    /**
     * Set the number of seconds to wait after initialization before
     * starting the scheduler asynchronously. Default is 0, meaning
     * immediate synchronous startup on initialization of this bean.
     * <p>Setting this to 10 or 20 seconds makes sense if no jobs
     * should be run before the entire application has started up.
     */
    public void setStartupDelay(int startupDelay) {
        this.startupDelay = startupDelay;
    }

    /**
     * Set whether to expose the Spring-managed {@link Scheduler} instance in the
     * Quartz {@link SchedulerRepository}. Default is "false", since the Spring-managed
     * Scheduler is usually exclusively intended for access within the Spring context.
     * <p>Switch this flag to "true" in order to expose the Scheduler globally.
     * This is not recommended unless you have an existing Spring application that
     * relies on this behavior. Note that such global exposure was the accidental
     * default in earlier Spring versions; this has been fixed as of Spring 2.5.6.
     */
    public void setExposeSchedulerInRepository(boolean exposeSchedulerInRepository) {
        this.exposeSchedulerInRepository = exposeSchedulerInRepository;
    }

    /**
     * Set whether to wait for running jobs to complete on shutdown.
     * <p>Default is "false". Switch this to "true" if you prefer
     * fully completed jobs at the expense of a longer shutdown phase.
     * @see org.quartz.Scheduler#shutdown(boolean)
     */
    public void setWaitForJobsToCompleteOnShutdown(boolean waitForJobsToCompleteOnShutdown) {
        this.waitForJobsToCompleteOnShutdown = waitForJobsToCompleteOnShutdown;
    }

    @Override
    public void setBeanName(String name) {
        this.beanName = name;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    // ---------------------------------------------------------------------
    // Implementation of InitializingBean interface
    // ---------------------------------------------------------------------
    @Override
    public void afterPropertiesSet() throws Exception {
        if (this.dataSource == null && this.nonTransactionalDataSource != null) {
            this.dataSource = this.nonTransactionalDataSource;
        }
        if (this.applicationContext != null && this.resourceLoader == null) {
            this.resourceLoader = this.applicationContext;
        }
        // Initialize the Scheduler instance...
        this.scheduler = prepareScheduler(prepareSchedulerFactory());
        try {
            registerListeners();
            registerJobsAndTriggers();
        } catch (Exception ex) {
            try {
                this.scheduler.shutdown(true);
            } catch (Exception ex2) {
                logger.debug("Scheduler shutdown exception after registration failure", ex2);
            }
            throw ex;
        }
    }

    /**
     * Create a SchedulerFactory if necessary and apply locally defined Quartz properties to it.
     * @return the initialized SchedulerFactory
     */
    private SchedulerFactory prepareSchedulerFactory() throws SchedulerException, IOException {
        SchedulerFactory schedulerFactory = this.schedulerFactory;
        if (schedulerFactory == null) {
            // Create local SchedulerFactory instance (typically a StdSchedulerFactory)
            schedulerFactory = BeanUtils.instantiateClreplaced(this.schedulerFactoryClreplaced);
            if (schedulerFactory instanceof StdSchedulerFactory) {
                initSchedulerFactory((StdSchedulerFactory) schedulerFactory);
            } else if (this.configLocation != null || this.quartzProperties != null || this.taskExecutor != null || this.dataSource != null) {
                throw new IllegalArgumentException("StdSchedulerFactory required for applying Quartz properties: " + schedulerFactory);
            }
        // Otherwise, no local settings to be applied via StdSchedulerFactory.initialize(Properties)
        }
        // Otherwise, replacedume that externally provided factory has been initialized with appropriate settings
        return schedulerFactory;
    }

    /**
     * Initialize the given SchedulerFactory, applying locally defined Quartz properties to it.
     * @param schedulerFactory the SchedulerFactory to initialize
     */
    private void initSchedulerFactory(StdSchedulerFactory schedulerFactory) throws SchedulerException, IOException {
        Properties mergedProps = new Properties();
        if (this.resourceLoader != null) {
            mergedProps.setProperty(StdSchedulerFactory.PROP_SCHED_CLreplaced_LOAD_HELPER_CLreplaced, ResourceLoaderClreplacedLoadHelper.clreplaced.getName());
        }
        if (this.taskExecutor != null) {
            mergedProps.setProperty(StdSchedulerFactory.PROP_THREAD_POOL_CLreplaced, LocalTaskExecutorThreadPool.clreplaced.getName());
        } else {
            // Set necessary default properties here, as Quartz will not apply
            // its default configuration when explicitly given properties.
            mergedProps.setProperty(StdSchedulerFactory.PROP_THREAD_POOL_CLreplaced, SimpleThreadPool.clreplaced.getName());
            mergedProps.setProperty(PROP_THREAD_COUNT, Integer.toString(DEFAULT_THREAD_COUNT));
        }
        if (this.configLocation != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Loading Quartz config from [" + this.configLocation + "]");
            }
            PropertiesLoaderUtils.fillProperties(mergedProps, this.configLocation);
        }
        CollectionUtils.mergePropertiesIntoMap(this.quartzProperties, mergedProps);
        if (this.dataSource != null) {
            mergedProps.setProperty(StdSchedulerFactory.PROP_JOB_STORE_CLreplaced, LocalDataSourceJobStore.clreplaced.getName());
        }
        // Determine scheduler name across local settings and Quartz properties...
        if (this.schedulerName != null) {
            mergedProps.setProperty(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, this.schedulerName);
        } else {
            String nameProp = mergedProps.getProperty(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME);
            if (nameProp != null) {
                this.schedulerName = nameProp;
            } else if (this.beanName != null) {
                mergedProps.setProperty(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, this.beanName);
                this.schedulerName = this.beanName;
            }
        }
        schedulerFactory.initialize(mergedProps);
    }

    private Scheduler prepareScheduler(SchedulerFactory schedulerFactory) throws SchedulerException {
        if (this.resourceLoader != null) {
            // Make given ResourceLoader available for SchedulerFactory configuration.
            configTimeResourceLoaderHolder.set(this.resourceLoader);
        }
        if (this.taskExecutor != null) {
            // Make given TaskExecutor available for SchedulerFactory configuration.
            configTimeTaskExecutorHolder.set(this.taskExecutor);
        }
        if (this.dataSource != null) {
            // Make given DataSource available for SchedulerFactory configuration.
            configTimeDataSourceHolder.set(this.dataSource);
        }
        if (this.nonTransactionalDataSource != null) {
            // Make given non-transactional DataSource available for SchedulerFactory configuration.
            configTimeNonTransactionalDataSourceHolder.set(this.nonTransactionalDataSource);
        }
        // Get Scheduler instance from SchedulerFactory.
        try {
            Scheduler scheduler = createScheduler(schedulerFactory, this.schedulerName);
            populateSchedulerContext(scheduler);
            if (!this.jobFactorySet && !(scheduler instanceof RemoteScheduler)) {
                // Use AdaptableJobFactory as default for a local Scheduler, unless when
                // explicitly given a null value through the "jobFactory" bean property.
                this.jobFactory = new AdaptableJobFactory();
            }
            if (this.jobFactory != null) {
                if (this.applicationContext != null && this.jobFactory instanceof ApplicationContextAware) {
                    ((ApplicationContextAware) this.jobFactory).setApplicationContext(this.applicationContext);
                }
                if (this.jobFactory instanceof SchedulerContextAware) {
                    ((SchedulerContextAware) this.jobFactory).setSchedulerContext(scheduler.getContext());
                }
                scheduler.setJobFactory(this.jobFactory);
            }
            return scheduler;
        } finally {
            if (this.resourceLoader != null) {
                configTimeResourceLoaderHolder.remove();
            }
            if (this.taskExecutor != null) {
                configTimeTaskExecutorHolder.remove();
            }
            if (this.dataSource != null) {
                configTimeDataSourceHolder.remove();
            }
            if (this.nonTransactionalDataSource != null) {
                configTimeNonTransactionalDataSourceHolder.remove();
            }
        }
    }

    /**
     * Create the Scheduler instance for the given factory and scheduler name.
     * Called by {@link #afterPropertiesSet}.
     * <p>The default implementation invokes SchedulerFactory's {@code getScheduler}
     * method. Can be overridden for custom Scheduler creation.
     * @param schedulerFactory the factory to create the Scheduler with
     * @param schedulerName the name of the scheduler to create
     * @return the Scheduler instance
     * @throws SchedulerException if thrown by Quartz methods
     * @see #afterPropertiesSet
     * @see org.quartz.SchedulerFactory#getScheduler
     */
    protected Scheduler createScheduler(SchedulerFactory schedulerFactory, @Nullable String schedulerName) throws SchedulerException {
        // Override thread context ClreplacedLoader to work around naive Quartz ClreplacedLoadHelper loading.
        Thread currentThread = Thread.currentThread();
        ClreplacedLoader threadContextClreplacedLoader = currentThread.getContextClreplacedLoader();
        boolean overrideClreplacedLoader = (this.resourceLoader != null && this.resourceLoader.getClreplacedLoader() != threadContextClreplacedLoader);
        if (overrideClreplacedLoader) {
            currentThread.setContextClreplacedLoader(this.resourceLoader.getClreplacedLoader());
        }
        try {
            SchedulerRepository repository = SchedulerRepository.getInstance();
            synchronized (repository) {
                Scheduler existingScheduler = (schedulerName != null ? repository.lookup(schedulerName) : null);
                Scheduler newScheduler = schedulerFactory.getScheduler();
                if (newScheduler == existingScheduler) {
                    throw new IllegalStateException("Active Scheduler of name '" + schedulerName + "' already registered " + "in Quartz SchedulerRepository. Cannot create a new Spring-managed Scheduler of the same name!");
                }
                if (!this.exposeSchedulerInRepository) {
                    // Need to remove it in this case, since Quartz shares the Scheduler instance by default!
                    SchedulerRepository.getInstance().remove(newScheduler.getSchedulerName());
                }
                return newScheduler;
            }
        } finally {
            if (overrideClreplacedLoader) {
                // Reset original thread context ClreplacedLoader.
                currentThread.setContextClreplacedLoader(threadContextClreplacedLoader);
            }
        }
    }

    /**
     * Expose the specified context attributes and/or the current
     * ApplicationContext in the Quartz SchedulerContext.
     */
    private void populateSchedulerContext(Scheduler scheduler) throws SchedulerException {
        // Put specified objects into Scheduler context.
        if (this.schedulerContextMap != null) {
            scheduler.getContext().putAll(this.schedulerContextMap);
        }
        // Register ApplicationContext in Scheduler context.
        if (this.applicationContextSchedulerContextKey != null) {
            if (this.applicationContext == null) {
                throw new IllegalStateException("SchedulerFactoryBean needs to be set up in an ApplicationContext " + "to be able to handle an 'applicationContextSchedulerContextKey'");
            }
            scheduler.getContext().put(this.applicationContextSchedulerContextKey, this.applicationContext);
        }
    }

    /**
     * Start the Quartz Scheduler, respecting the "startupDelay" setting.
     * @param scheduler the Scheduler to start
     * @param startupDelay the number of seconds to wait before starting
     * the Scheduler asynchronously
     */
    protected void startScheduler(final Scheduler scheduler, final int startupDelay) throws SchedulerException {
        if (startupDelay <= 0) {
            logger.info("Starting Quartz Scheduler now");
            scheduler.start();
        } else {
            if (logger.isInfoEnabled()) {
                logger.info("Will start Quartz Scheduler [" + scheduler.getSchedulerName() + "] in " + startupDelay + " seconds");
            }
            // Not using the Quartz startDelayed method since we explicitly want a daemon
            // thread here, not keeping the JVM alive in case of all other threads ending.
            Thread schedulerThread = new Thread() {

                @Override
                public void run() {
                    try {
                        TimeUnit.SECONDS.sleep(startupDelay);
                    } catch (InterruptedException ex) {
                        Thread.currentThread().interrupt();
                    // simply proceed
                    }
                    if (logger.isInfoEnabled()) {
                        logger.info("Starting Quartz Scheduler now, after delay of " + startupDelay + " seconds");
                    }
                    try {
                        scheduler.start();
                    } catch (SchedulerException ex) {
                        throw new SchedulingException("Could not start Quartz Scheduler after delay", ex);
                    }
                }
            };
            schedulerThread.setName("Quartz Scheduler [" + scheduler.getSchedulerName() + "]");
            schedulerThread.setDaemon(true);
            schedulerThread.start();
        }
    }

    // ---------------------------------------------------------------------
    // Implementation of FactoryBean interface
    // ---------------------------------------------------------------------
    @Override
    public Scheduler getScheduler() {
        replacedert.state(this.scheduler != null, "No Scheduler set");
        return this.scheduler;
    }

    @Override
    @Nullable
    public Scheduler getObject() {
        return this.scheduler;
    }

    @Override
    public Clreplaced<? extends Scheduler> getObjectType() {
        return (this.scheduler != null ? this.scheduler.getClreplaced() : Scheduler.clreplaced);
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    // ---------------------------------------------------------------------
    // Implementation of SmartLifecycle interface
    // ---------------------------------------------------------------------
    @Override
    public void start() throws SchedulingException {
        if (this.scheduler != null) {
            try {
                startScheduler(this.scheduler, this.startupDelay);
            } catch (SchedulerException ex) {
                throw new SchedulingException("Could not start Quartz Scheduler", ex);
            }
        }
    }

    @Override
    public void stop() throws SchedulingException {
        if (this.scheduler != null) {
            try {
                this.scheduler.standby();
            } catch (SchedulerException ex) {
                throw new SchedulingException("Could not stop Quartz Scheduler", ex);
            }
        }
    }

    @Override
    public boolean isRunning() throws SchedulingException {
        if (this.scheduler != null) {
            try {
                return !this.scheduler.isInStandbyMode();
            } catch (SchedulerException ex) {
                return false;
            }
        }
        return false;
    }

    // ---------------------------------------------------------------------
    // Implementation of DisposableBean interface
    // ---------------------------------------------------------------------
    /**
     * Shut down the Quartz scheduler on bean factory shutdown,
     * stopping all scheduled jobs.
     */
    @Override
    public void destroy() throws SchedulerException {
        if (this.scheduler != null) {
            logger.info("Shutting down Quartz Scheduler");
            this.scheduler.shutdown(this.waitForJobsToCompleteOnShutdown);
        }
    }
}

18 View Complete Implementation : QuartzTriggerDriver.java
Copyright Eclipse Public License 1.0
Author : eclipse
private static Scheduler getScheduler() throws SchedulerNotAvailableException {
    SchedulerFactory sf = new StdSchedulerFactory();
    Scheduler scheduler;
    try {
        scheduler = sf.getScheduler();
    } catch (SchedulerException se) {
        throw new SchedulerNotAvailableException(se);
    }
    return scheduler;
}

17 View Complete Implementation : QuartzCronPoller.java
Copyright Apache License 2.0
Author : adaptris
/**
 * <p>
 * Implementation of <code>Poller</code> which provides <i>cron</i> style scheduled polling based on the <a
 * href="http://www.quartz-scheduler.org/">Quartz project</a>.
 * </p>
 * <p>
 * A single Quartz Scheduler per Adapter (or Clreplacedloader) is used by all configured instances of QuartzCronPoller.
 * </p>
 * <p>
 * A file <code>quartz.properties</code> is used to configure the Scheduler. This file is included in quartz.jar with default
 * settings which should be suitable for most of our purposes. In an Adapter deployment with more than 10 consumers using
 * {@link QuartzCronPoller} you may wish to increase the size of the <code>Scheduler</code>'s thread pool. To do this place the
 * amended copy of the properties file in the Adapter Framework config directory.
 * </p>
 * <p>
 * For deployments with less 10 consumers using this {@link Poller}, there is little or no benefit in increasing the size of the
 * thread pool; each {@link AdaptrisPollingConsumer} instance is single threaded.
 * </p>
 * <p>
 * Although this clreplaced was created to allow 'every weekday at 10am' style scheduling, it can also be used to poll e.g. 'every 10
 * seconds'. Where a poll has not completed before the next scheduled poll is triggered, the subsequent poll will fail quietly,
 * because it cannot obtain the replacedociated lock.
 * </p>
 * <p>
 * The following is copied directly from the Quartz CronExpression javadocs.
 * </p>
 * </p> Cron expressions are comprised of 6 required fields and one optional field separated by white space. The fields respectively
 * are described as follows:
 *
 * <table cellspacing="8">
 * <tr>
 * <th align="left">Field Name</th>
 * <th align="left"> </th>
 * <th align="left">Allowed Values</th>
 * <th align="left"> </th>
 * <th align="left">Allowed Special Characters</th>
 *
 * </tr>
 * <tr>
 * <td align="left"><code>Seconds</code></td>
 * <td align="left"> </td>
 * <td align="left"><code>0-59</code></td>
 * <td align="left"> </td>
 * <td align="left"><code>, - * /</code></td>
 *
 * </tr>
 * <tr>
 * <td align="left"><code>Minutes</code></td>
 * <td align="left"> </td>
 * <td align="left"><code>0-59</code></td>
 * <td align="left"> </td>
 * <td align="left"><code>, - * /</code></td>
 *
 * </tr>
 * <tr>
 * <td align="left"><code>Hours</code></td>
 * <td align="left"> </td>
 * <td align="left"><code>0-23</code></td>
 * <td align="left"> </td>
 * <td align="left"><code>, - * /</code></td>
 *
 * </tr>
 * <tr>
 * <td align="left"><code>Day-of-month</code></td>
 * <td align="left"> </td>
 * <td align="left"><code>1-31</code></td>
 * <td align="left"> </td>
 * <td align="left"><code>, - * ? / L W C</code></td>
 *
 * </tr>
 * <tr>
 * <td align="left"><code>Month</code></td>
 * <td align="left"> </td>
 * <td align="left"><code>1-12 or JAN-DEC</code></td>
 * <td align="left"> </td>
 * <td align="left"><code>, - * /</code></td>
 *
 * </tr>
 * <tr>
 * <td align="left"><code>Day-of-Week</code></td>
 * <td align="left"> </td>
 * <td align="left"><code>1-7 or SUN-SAT</code></td>
 * <td align="left"> </td>
 * <td align="left"><code>, - * ? / L #</code></td>
 *
 * </tr>
 * <tr>
 * <td align="left"><code>Year (Optional)</code></td>
 * <td align="left"> </td>
 * <td align="left"><code>empty, 1970-2099</code></td>
 * <td align="left"> </td>
 * <td align="left"><code>, - * /</code></td>
 * </tr>
 * </table>
 * </p> The '*' character is used to specify all values. For example, "*" in the minute field means "every minute". </p>
 * <p>
 * The '?' character is allowed for the day-of-month and day-of-week fields. It is used to specify 'no specific value'. This is
 * useful when you need to specify something in one of the two fileds, but not the other.
 * </p>
 * <p>
 * The '-' character is used to specify ranges For example "10-12" in the hour field means "the hours 10, 11 and 12".
 * </p>
 * <p>
 * The ',' character is used to specify additional values. For example "MON,WED,FRI" in the day-of-week field means "the days
 * Monday, Wednesday, and Friday".
 * </p>
 * <p>
 * The '/' character is used to specify increments. For example "0/15" in the seconds field means "the seconds 0, 15, 30, and 45".
 * And "5/15" in the seconds field means "the seconds 5, 20, 35, and 50". Specifying '*' before the '/' is equivalent to specifying
 * 0 is the value to start with. Essentially, for each field in the expression, there is a set of numbers that can be turned on or
 * off. For seconds and minutes, the numbers range from 0 to 59. For hours 0 to 23, for days of the month 0 to 31, and for months 1
 * to 12. The "/" character simply helps you turn on every "nth" value in the given set. Thus "7/6" in the month field only turns on
 * month "7", it does NOT mean every 6th month, please note that subtlety.
 * </p>
 * <p>
 * The 'L' character is allowed for the day-of-month and day-of-week fields. This character is short-hand for "last", but it has
 * different meaning in each of the two fields. For example, the value "L" in the day-of-month field means
 * "the last day of the month" - day 31 for January, day 28 for February on non-leap years. If used in the day-of-week field by
 * itself, it simply means "7" or "SAT". But if used in the day-of-week field after another value, it means
 * "the last xxx day of the month" - for example "6L" means "the last friday of the month". When using the 'L' option, it is
 * important not to specify lists, or ranges of values, as you'll get confusing results.
 * </p>
 * <p>
 * The 'W' character is allowed for the day-of-month field. This character is used to specify the weekday (Monday-Friday) nearest
 * the given day. As an example, if you were to specify "15W" as the value for the day-of-month field, the meaning is:
 * "the nearest weekday to the 15th of the month". So if the 15th is a Saturday, the trigger will fire on Friday the 14th. If the
 * 15th is a Sunday, the trigger will fire on Monday the 16th. If the 15th is a Tuesday, then it will fire on Tuesday the 15th.
 * However if you specify "1W" as the value for day-of-month, and the 1st is a Saturday, the trigger will fire on Monday the 3rd, as
 * it will not 'jump' over the boundary of a month's days. The 'W' character can only be specified when the day-of-month is a single
 * day, not a range or list of days.
 * </p>
 * <p>
 * The 'L' and 'W' characters can also be combined for the day-of-month expression to yield 'LW', which translates to
 * "last weekday of the month".
 * </p>
 * <p>
 * The '#' character is allowed for the day-of-week field. This character is used to specify "the nth" day of the month. For
 * example, the value of "6#3" in the day-of-week field means the third Friday of the month (day 6 = Friday and "#3" = the 3rd one
 * in the month). Other examples: "2#1" = the first Monday of the month and "4#5" = the fifth Wednesday of the month. Note that if
 * you specify "#5" and there is not 5 of the given day-of-week in the month, then no firing will occur that month.
 * </p>
 * <p>
 * The legal characters and the names of months and days of the week are not case sensitive.
 * </p>
 * <p>
 * Support for specifying both a day-of-week and a day-of-month value is not complete (you'll need to use the '?' character in on of
 * these fields).
 * </p>
 *
 * @config quartz-cron-poller
 */
@XStreamAlias("quartz-cron-poller")
@DisplayOrder(order = { "cronExpression", "useCustomThreadPool", "quartzId", "schedulerGroup" })
public clreplaced QuartzCronPoller extends PollerImp {

    private transient SchedulerFactory factory;

    private transient Scheduler scheduler;

    private transient JobDetail jobDetail;

    // used for Job, Trigger and Listener
    private transient String registeredQuartzId;

    private transient String registeredSchedulerGroup;

    // marshalled
    private String cronExpression;

    @AdvancedConfig
    private String quartzId;

    @AdvancedConfig
    private String schedulerGroup;

    @AdvancedConfig(rare = true)
    @InputFieldDefault(value = "true")
    private Boolean useCustomThreadPool;

    private static final transient FifoMutexLock lock = new FifoMutexLock();

    /**
     * <p>
     * Creates a new instance. The default cron expression is <code>0 0,10,20,30,40,50 * * * ?</code> (every ten minutes every day,
     * from on the hour).
     * </p>
     */
    public QuartzCronPoller() {
        // factory = new StdSchedulerFactory();
        setCronExpression("0 0,10,20,30,40,50 * * * ?");
    }

    public QuartzCronPoller(String exp) {
        this();
        setCronExpression(exp);
    }

    public QuartzCronPoller(String exp, String quartzId) {
        this();
        setCronExpression(exp);
        setQuartzId(quartzId);
    }

    public QuartzCronPoller(String exp, Boolean useCustomThreadPool) {
        this();
        setCronExpression(exp);
        setUseCustomThreadPool(useCustomThreadPool);
    }

    /**
     * @see com.adaptris.core.AdaptrisComponent#init()
     */
    @Override
    public void init() throws CoreException {
        try {
            factory = new StdSchedulerFactory(createQuartzProperties());
            scheduler = createAndStartScheduler(factory);
            registeredQuartzId = generateQuartzId();
            log.trace("Using QuartzId [" + registeredQuartzId + "]");
            registeredSchedulerGroup = generateSchedulerGroup();
            // Create the job
            jobDetail = newJob(MyProcessJob.clreplaced).withIdenreplacedy(getJobKey()).build();
            JobDataMap jobDataMap = jobDetail.getJobDataMap();
            jobDataMap.put("consumer", this);
            // Create the cron trigger
            Trigger cronTrigger = newTrigger().withIdenreplacedy(registeredQuartzId, registeredSchedulerGroup).withSchedule(cronSchedule(getCronExpression()).withMisfireHandlingInstructionDoNothing()).build();
            // Update the scheduler
            scheduler.scheduleJob(jobDetail, cronTrigger);
            scheduler.pauseJob(getJobKey());
            log.trace("[" + registeredQuartzId + "] scheduled in group [" + registeredSchedulerGroup + "]");
        } catch (Exception e) {
            throw new CoreException(e);
        }
    }

    private String generateQuartzId() {
        String result;
        if (!isEmpty(getQuartzId())) {
            result = getQuartzId();
        } else {
            if (retrieveConsumer().getDestination() != null) {
                result = retrieveConsumer().getDestination().getUniqueId() + "@" + Integer.toHexString(hashCode());
            } else {
                result = "NoDestination@" + Integer.toHexString(hashCode());
            }
        }
        return result;
    }

    String generateSchedulerGroup() {
        String result = Scheduler.DEFAULT_GROUP;
        if (!isEmpty(getSchedulerGroup())) {
            result = getSchedulerGroup();
        }
        return result;
    }

    private static Scheduler createAndStartScheduler(SchedulerFactory fac) throws SchedulerException, InterruptedException {
        Scheduler s = null;
        try {
            lock.acquire();
            s = fac.getScheduler();
            s.start();
        } finally {
            lock.release();
        }
        return s;
    }

    /**
     * @see com.adaptris.core.AdaptrisComponent#start()
     */
    @Override
    public void start() throws CoreException {
        try {
            scheduler.resumeJob(getJobKey());
            log.trace("[" + registeredQuartzId + "] resumed in group [" + registeredSchedulerGroup + "]");
        } catch (Exception e) {
            throw new CoreException(e);
        }
    }

    @Override
    public void stop() {
        pauseJob();
    }

    @Override
    public void close() {
        pauseJob();
        deleteJob();
    }

    void pauseJob() {
        try {
            if (scheduler != null) {
                scheduler.pauseJob(getJobKey());
                log.trace("[{}] paused in group [{}]", registeredQuartzId, registeredSchedulerGroup);
            }
        } catch (Exception e) {
        // log.trace("Failed to stop component cleanly, logging exception for informational purposes only", e);
        }
    }

    void deleteJob() {
        try {
            if (scheduler != null) {
                scheduler.deleteJob(getJobKey());
                log.trace("[{}] removed from group [{}]", registeredQuartzId, registeredSchedulerGroup);
            }
        } catch (SchedulerException e) {
        // log.trace("Failed to shutdown component cleanly, logging exception for informational purposes only", e);
        }
    }

    /**
     * <p>
     * Return the <i>cron</i> expression to use.
     * </p>
     *
     * @return the <i>cron</i> expression to use
     */
    public String getCronExpression() {
        return cronExpression;
    }

    /**
     * <p>
     * Sets the <i>cron</i> expression to use.
     * </p>
     *
     * @param s the <i>cron</i> expression to use
     */
    public void setCronExpression(String s) {
        cronExpression = s;
    }

    public String getName() {
        return registeredQuartzId;
    }

    public String getQuartzId() {
        return quartzId;
    }

    /**
     * Set the quartz id that will be registered.
     * <p>
     * The quartz id acts as the name of the job, the name of the trigger, and the name of the triggerlistener. You should not need to
     * configure this unless you are customising quartz.properties heavily; it is included for completeness.
     * </p>
     *
     * @param s the quartz id; if null or empty, then one will be generated for you.
     */
    public void setQuartzId(String s) {
        quartzId = s;
    }

    public String getSchedulerGroup() {
        return schedulerGroup;
    }

    /**
     * Set the scheduler group.
     * <p>
     * The 'group' feature may be useful for creating logical groupings or categorizations of Jobs. You should not need to configure
     * this but is included for completeness.
     * </p>
     *
     * @param s the scheduler group; if null or empty, then {@link Scheduler#DEFAULT_GROUP} is used ('DEFAULT')
     */
    public void setSchedulerGroup(String s) {
        schedulerGroup = s;
    }

    /**
     * Creates a job key that encapsulates the job name and group name. This is used for the various Scheduler methods
     *
     * @return new JobKey Instance
     */
    protected JobKey getJobKey() {
        return jobKey(registeredQuartzId, registeredSchedulerGroup);
    }

    // Job that executes when cron is triggered
    public static clreplaced MyProcessJob implements Job {

        @Override
        public void execute(JobExecutionContext context) throws JobExecutionException {
            JobDataMap map = context.getJobDetail().getJobDataMap();
            QuartzCronPoller poller = (QuartzCronPoller) map.get("consumer");
            poller.processMessages();
        }
    }

    private Properties createQuartzProperties() throws CoreException {
        try {
            Properties result = PropertyHelper.load(() -> {
                return openQuartzProperties();
            });
            result.put(StdSchedulerFactory.PROP_SCHED_MAKE_SCHEDULER_THREAD_DAEMON, Boolean.TRUE.toString());
            result.putAll(System.getProperties());
            if (useCustomThreadPool()) {
                result.put(StdSchedulerFactory.PROP_THREAD_POOL_CLreplaced, NonBlockingQuartzThreadPool.clreplaced.getCanonicalName());
            }
            // result.put(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, schedulerName);
            // result.put("org.quartz.plugin.shutdownhook.clreplaced",
            // org.quartz.plugins.management.ShutdownHookPlugin.clreplaced.getCanonicalName());
            // result.put("org.quartz.plugin.shutdownhook.cleanShutdown", Boolean.FALSE.toString());
            return result;
        } catch (Exception e) {
            throw ExceptionHelper.wrapCoreException(e);
        }
    }

    private InputStream find(String... resources) throws IOException {
        ClreplacedLoader cl = getClreplaced().getClreplacedLoader();
        InputStream in = null;
        for (String res : resources) {
            in = cl.getResourcereplacedtream(res);
            if (in != null) {
                log.trace("Using quartz properties from clreplacedpath : {}", res);
                break;
            }
        }
        // It may just return null; ultimately it's user error, do we care, an NPE would be OK here.
        // but possibly not informative
        return in;
    }

    private InputStream openQuartzProperties() throws IOException {
        String requestedFile = System.getProperty(StdSchedulerFactory.PROPERTIES_FILE);
        String propFileName = requestedFile != null ? requestedFile : "quartz.properties";
        File propFile = new File(propFileName);
        if (propFile.exists()) {
            log.trace("Using quartz properties from file : {}", propFile.getCanonicalPath());
            return new FileInputStream(propFile);
        } else if (requestedFile != null) {
            // It may just return null; ultimately it's user error, do we care, an NPE would be OK here.
            // but possibly not informative
            log.trace("Using quartz properties from clreplacedpath : {}", requestedFile);
            return Thread.currentThread().getContextClreplacedLoader().getResourcereplacedtream(requestedFile);
        } else {
            return find("quartz.properties", "/quartz.properties", "org/quartz/quartz.properties");
        }
    }

    public Boolean getUseCustomThreadPool() {
        return useCustomThreadPool;
    }

    /**
     * If set to true, then we use {@link NonBlockingQuartzThreadPool} as the threadpool implementation for quartz.
     * <p>
     * If set to false, then the default {@code quartz.properties} are not modified when initialising the {@link StdSchedulerFactory};
     * however, mixing and matching thread pools between different instances is discouraged and may lead to undefined behaviour.
     * </p>
     *
     * @param b false to disable our own thread pool, default true.
     */
    public void setUseCustomThreadPool(Boolean b) {
        this.useCustomThreadPool = b;
    }

    protected boolean useCustomThreadPool() {
        return BooleanUtils.toBooleanDefaultIfNull(getUseCustomThreadPool(), true);
    }
}