gpt4 book ai didi

Java Quartz Scheduler 我的配置存在错误或问题

转载 作者:行者123 更新时间:2023-12-01 15:16:08 26 4
gpt4 key购买 nike

我通过使用实现 ServletContextListener 的 Servlet 在 strut2 Web 应用程序中添加了 QuartzFramework。在使用quartz属性的servlet中,我创建了一个名为“AsyncJobsQuartz”的Quartz实例,并使用scheduler.start()启动它。

使用 JobStore 计划作业,因此每天都会在计划时间执行作业。但问题是当作业正在执行时,我无法在其他地方使用调度程序实例。即,在其他操作中,我尝试使用获取实例

scheduler = schedulerFactory.getScheduler("ASYNC_JOBS_SCHEDULER");

但是我将调度程序设置为空,后来的scheduler.getJobGroupNames()是空指针异常。但一旦作业结束,调度程序就会返回并包含所有详细信息。

我很困惑,我是否错过了一些设置,或者 Quartz 是否存在错误。请给我一个解决方案。

实例化并启动调度程序的类(servlet)。我没有使用quartz.properties文件,因为根据说明,我不应该多次指定数据库凭据,即在hibernate.cfg.xml中,然后在quartz.properties中。

package com.generalsentiment.test.quartz;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.lang.reflect.Field;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.common.collect.Maps;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.ConfigurationException;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.hibernate.SessionFactory;
import org.hibernate.impl.SessionFactoryImpl;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerMetaData;
import org.quartz.impl.matchers.GroupMatcher;

import com.generalsentiment.util.HibernateUtil;
import com.generalsentiment.util.quartz.SchedulerConstants;
import com.generalsentiment.util.quartz.QuartzSchedulerUtil;
import org.apache.commons.configuration.*;

public class QuartzServlet implements ServletContextListener {

private Map<String, String> existingJobsList;
private String hibernateConnectionUrl;
private SessionFactory sessionFactory;

@Override
public void contextInitialized(ServletContextEvent sce) {
try {
Properties properties = new Properties();
Field f = SessionFactoryImpl.class.getDeclaredField("properties");
f.setAccessible(true);
sessionFactory = HibernateUtil.getSessionFactory();

Properties p = (Properties) f.get(sessionFactory);
properties.setProperty("org.quartz.scheduler.instanceName", SchedulerConstants.SCHEDULER_INSTANCE_NAME);
properties.setProperty("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
properties.setProperty("org.quartz.threadPool.threadCount", "4");
properties.setProperty("org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread", "true");

properties.setProperty("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreCMT");
properties.setProperty("org.quartz.jobStore.driverDelegateClass", "org.quartz.impl.jdbcjobstore.StdJDBCDelegate");
properties.setProperty("org.quartz.jobStore.useProperties", "false");
properties.setProperty("org.quartz.jobStore.dataSource", "tasksDataStoreContainer");
properties.setProperty("org.quartz.jobStore.nonManagedTXDataSource", "tasksDataStoreQuartz");
properties.setProperty("org.quartz.jobStore.tablePrefix", "QRTZ_");
properties.setProperty("org.quartz.jobStore.misfireThreshold", "60000");
properties.setProperty("org.quartz.jobStore.isClustered", "false");

properties.setProperty("org.quartz.dataSource.tasksDataStoreContainer.driver", p.getProperty("hibernate.connection.driver_class"));
properties.setProperty("org.quartz.dataSource.tasksDataStoreContainer.URL", p.getProperty("hibernate.connection.url"));
properties.setProperty("org.quartz.dataSource.tasksDataStoreContainer.user", p.getProperty("hibernate.connection.username"));
properties.setProperty("org.quartz.dataSource.tasksDataStoreContainer.password", p.getProperty("hibernate.connection.password"));
properties.setProperty("org.quartz.dataSource.tasksDataStoreContainer.maxConnections", "20");

properties.setProperty("org.quartz.dataSource.tasksDataStoreQuartz.driver", p.getProperty("hibernate.connection.driver_class"));
properties.setProperty("org.quartz.dataSource.tasksDataStoreQuartz.URL", p.getProperty("hibernate.connection.url"));
properties.setProperty("org.quartz.dataSource.tasksDataStoreQuartz.user", p.getProperty("hibernate.connection.username"));
properties.setProperty("org.quartz.dataSource.tasksDataStoreQuartz.password", p.getProperty("hibernate.connection.password"));
properties.setProperty("org.quartz.dataSource.tasksDataStoreQuartz.maxConnections", "20");
hibernateConnectionUrl = p.getProperty("hibernate.connection.url");


System.out.println("THE APPLICATION STARTED");

// First we must get a reference to a scheduler
existingJobsList = Maps.newHashMap();
Scheduler scheduler = QuartzSchedulerUtil.initiateSchedulerFactory(properties);
System.out.println("------- Initialization Complete --------");
System.out.println("------- Scheduling Jobs ----------------");

System.out.println("------- Starting Scheduler ----------------");
List<String> jobGroupNames = scheduler.getJobGroupNames();
for (String current : jobGroupNames) {
for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.<JobKey>groupEquals(current))) {
existingJobsList.put(jobKey.getName(), jobKey.getGroup());
}
}

if (!existingJobsList.containsKey("ExportOrgUsersToFileJob")) {

JobDetail job = newJob(ExportOrgUsersToFileJob.class).withIdentity("ExportOrgUsersToFileJob",
SchedulerConstants.JOBS_GROUP).build();

CronTrigger trigger = newTrigger().withIdentity("trigger@morning",
SchedulerConstants.TRIGGER_MORNING_GROUP).withSchedule(cronSchedule("00 10 15 * * ?")).build();
job.getJobDataMap().put("jobDescription", "Exports a particular Organization users to file");
job.getJobDataMap().put("jobStatus", SchedulerConstants.JOB_STATUS.PENDING);
Date ft = scheduler.scheduleJob(job, trigger);
}

if (!existingJobsList.containsKey("DownloadScoresJob")) {
JobDetail job1 = newJob(DownloadScoresJob.class).withIdentity("DownloadScoresJob",
SchedulerConstants.JOBS_GROUP).build();

CronTrigger trigger1 = newTrigger().withIdentity("trigger@evening",
SchedulerConstants.TRIGGER_EVENING_GROUP).withSchedule(cronSchedule("00 15 15 * * ?")).build();

job1.getJobDataMap().put("jobDescription", "Downloads involvement index scores for given synsets");
job1.getJobDataMap().put("jobStatus", SchedulerConstants.JOB_STATUS.PENDING);
Date ft1 = scheduler.scheduleJob(job1, trigger1);
}
// JobListener jobListener = new QuartzJobListener();
// scheduler.getListenerManager().addJobListener(jobListener, allJobs());

scheduler.start();

System.out.println("------- Started Scheduler -----------------");

SchedulerMetaData metaData = scheduler.getMetaData();
System.out.println("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");
} catch (IllegalAccessException ex) {
Logger.getLogger(QuartzServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchFieldException ex) {
Logger.getLogger(QuartzServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(QuartzServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (SchedulerException se) {
System.out.println(se);
} catch (ConfigurationException ex) {
Logger.getLogger(QuartzServlet.class.getName()).log(Level.SEVERE, null, ex);
}

}

@Override
public void contextDestroyed(ServletContextEvent sce) {
try {
Scheduler scheduler = QuartzSchedulerUtil.getCurrentScheduler();
if (scheduler != null) {
//to avoid NPE
scheduler.shutdown(true);
}
Thread.sleep(1000);
Driver mySqlDriver = DriverManager.getDriver(hibernateConnectionUrl);
DriverManager.deregisterDriver(mySqlDriver);
sessionFactory.close();
} catch (SchedulerException ex) {
Logger.getLogger(QuartzServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(QuartzServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(QuartzServlet.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("THE QUARTZ APPLICATION STOPPED");
}

public String getHibernateConnectionUrl() {
return hibernateConnectionUrl;
}

public void setHibernateConnectionUrl(String hibernateConnectionUrl) {
this.hibernateConnectionUrl = hibernateConnectionUrl;
}
}

最佳答案

我正在使用 Quartz v1.8.4 和 Struts2(并不是说我认为这在这里特别重要)。要在我的一项操作中访问调度程序,我必须使用以下命令。

    public Scheduler getScheduler() throws SchedulerException {
ServletContext context = this.getServletRequest().getSession().getServletContext();
SchedulerFactory factory = (StdSchedulerFactory) context.getAttribute("org.quartz.impl.StdSchedulerFactory.KEY");
return factory.getScheduler();
}

我的项目中的 Quartz jar 是quartz-1.8.4.jar 和quartz-oracle-1.8.4.jar。

我使用 Quartz 提供的 servlet 来初始化 Quartz,我只是在 web.xml 中定义了它:

<servlet> 
<servlet-name>QuartzInitializer</servlet-name>
<servlet-class>org.quartz.ee.servlet.QuartzInitializerServlet</servlet-class>
<init-param>
<param-name>shutdown-on-unload</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>

关于Java Quartz Scheduler 我的配置存在错误或问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11583701/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com