当前位置: 首页 > 知识库问答 >
问题:

Quartz作业无法使用Spring JpaRepository函数

夏振国
2023-03-14

Job1在org.eko.businessjobs.Job1.doperform(Job1.java:23)在org.eko.jobs.businessjoba.executeinternal(businessjoba.java:34)在org.springframework.scheduling.quartz.quartzjobbean.execute(quartzjobbean.java:75)在org.quartz.core.jobrunshell.run(jobrunshell.java:202)在org.quartz.simple.simplethreadpool空

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.8.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">

	<context:component-scan base-package="org.eko">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>
	
	<jpa:repositories base-package="org.eko.repository" />
	
	<task:annotation-driven/>

	<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
		id="entityManagerFactory">
		<property name="packagesToScan" value="org.eko.entity" />
		<property name="dataSource" ref="dataSource" />
		<property name="jpaProperties">
			<props>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
			</props>
		</property>
		<property name="persistenceProvider">
			<bean class="org.hibernate.jpa.HibernatePersistenceProvider" />
		</property>
	</bean>	
 
  <!-- 
 
 	<bean id="dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
      <property name = "url" value = "jdbc:mysql://localhost:3306/Simpli_bank_Scheduler"/>
      <property name = "username" value = "root"/>
      <property name = "password" value = "1234"/>
   </bean>
   
  -->
  
   <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    	<!-- Connection properties -->
    	<property name="driverClass" value="com.mysql.jdbc.Driver" />
    	<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/Simpli_bank_Scheduler" />
    	<property name="user" value="root" />
    	<property name="password" value="1234" />
    	
    	<!-- Pool properties -->
    	<property name="minPoolSize" value="5" />
    	<property name="maxPoolSize" value="200" />
    	<property name="acquireIncrement" value="1" />
    	<property name="maxStatements" value="500" />
    	<property name="idleConnectionTestPeriod" value="3000" />
    	<property name="loginTimeout" value="300" />
 	</bean>  
   
 	<tx:annotation-driven transaction-manager="transactionManager" />
	<bean class="org.springframework.orm.jpa.JpaTransactionManager"	id="transactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
<!-- 	
	<bean id="Job1" class="org.eko.jobs.BusinessJobA">
    	<property name="sessionFactory" ref="sessionFactory"> </property>
	</bean>
	
	<bean name="BusinessJobA" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <property name="jobClass">
            <bean factory-bean="Job1" factory-method="setJob1"></bean>
        </property>
	</bean>
	
 	<bean id="BusinessJobA" class="org.eko.jobs.BusinessJobA" />

 	<bean id="quartzJobFactory" class="org.eko.configuration.AutowiringSpringBeanJobFactory">
    	<property name="ignoredUnknownProperties" value="applicationContext"/>
	</bean>    

	<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    	<property name="dataSource" ref="dataSource"/>
    	<property name="transactionManager" ref="transactionManager"/>
    	<property name="jobFactory" ref="quartzJobFactory"/>
		<property name="overwriteExistingJobs" value="true"/> 
    
    	<property name="autoStartup" value="true" />
    	<property name="schedulerName" value="quartzScheduler"/>
    	<property name="applicationContextSchedulerContextKey" value="applicationContext"/>
	    <property name="waitForJobsToCompleteOnShutdown" value="false"/>
	    <property name="configLocation" value="classpath:quartz.properties" />
    	<property name="quartzProperties">
        <props>
            <prop key="org.quartz.jobStore.misfireThreshold">60000</prop>
            <prop key="org.quartz.threadPool.threadCount">50</prop>
            <prop key="org.quartz.scheduler.instanceName">AUTO</prop>
            <prop key="org.quartz.scheduler.instanceId">AUTO</prop>
            <prop key="org.quartz.scheduler.skipUpdateCheck">true</prop>
            <prop key="org.quartz.jobStore.class">org.quartz.impl.jdbcjobstore.JobStoreTX</prop>
            <prop key="org.quartz.threadPool.class">org.quartz.simpl.SimpleThreadPool</prop>
        </props>
    </property>
</bean>

<bean id="BusinessObjectA" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
    <property name="jobClass" value="org.eko.jobs.BusinessJobA"/>
</bean>

<bean id="BusinessObjectB" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
    <property name="jobClass" value="org.eko.jobs.BusinessJobB"/>
</bean>

<bean id="BusinessObjectC" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
    <property name="jobClass" value="org.eko.jobs.BusinessJobC"/>
</bean>

<bean id="BusinessObjectD" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
    <property name="jobClass" value="org.eko.jobs.BusinessJobD"/>
</bean>
-->
<!-- 
<bean name="businessJobA" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
    <property name="jobClass" value="org.eko.jobs.BusinessJobA"/>
    <property name="group" value="Group1"/>
</bean>

<task:annotation-driven/> 

<bean id="businessJobA" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">  
   <property name="jobClass" value="org.eko.jobs.BusinessJobA"/>  
   <property name="jobDataAsMap">  
     <map>  
       <entry key="name" value="Job1"/>  
     </map>  
   </property>  
   <property name="durability" value="true"/>  
 </bean> 

 <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">  
   <property name="jobDetail" ref="businessJobA" />  
   <property name="cronExpression" value="0/2 * * * * ?"/>  
 </bean> 
 
 <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
  <property name="jobDetails">  
    <list>  
      <ref bean="businessJobA" />  
    </list>  
  </property>  
  <property name="triggers">  
    <list>  
      <ref bean="cronTrigger" />  
    </list>  
  </property>  
 </bean> -->
 
 <bean id="job1" class="org.eko.BusinessJobs.Job1"/>
 <bean id="job2" class="org.eko.BusinessJobs.Job2"/>
 <bean id="job3" class="org.eko.BusinessJobs.Job3"/>
 <bean id="job4" class="org.eko.BusinessJobs.Job4"/>
 
 <bean id="job1job" class = "org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
  <property name="targetObject" ref="job1"/>  
  <property name="targetMethod" value="doPerform"/>  
 </bean>
 
 <bean id="job2job" class = "org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
  <property name="targetObject" ref="job2"/>  
  <property name="targetMethod" value="doPerform"/>  
 </bean>
 
 <bean id="job3job" class = "org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
  <property name="targetObject" ref="job3"/>  
  <property name="targetMethod" value="doPerform"/>  
 </bean>
 
 <bean id="job4job" class = "org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
  <property name="targetObject" ref="job4"/>  
  <property name="targetMethod" value="doPerform"/>  
 </bean>

 <bean id="simpleTrigger1" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">  
   <property name="jobDetail" ref="job1job" />  
   <property name="repeatInterval" value="5000" />  
   <property name="startDelay" value="1000" />
   <property name="repeatCount" value="5" />
 </bean>
 
 <bean id="simpleTrigger2" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">  
   <property name="jobDetail" ref="job2job" />  
   <property name="repeatInterval" value="5000" />  
   <property name="startDelay" value="1000" />
   <property name="repeatCount" value="5" />
 </bean>
 
 <bean id="simpleTrigger3" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">  
   <property name="jobDetail" ref="job3job" />  
   <property name="repeatInterval" value="5000" />  
   <property name="startDelay" value="1000" />
   <property name="repeatCount" value="5" />
 </bean>
 
 <bean id="simpleTrigger4" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">  
   <property name="jobDetail" ref="job4job" />  
   <property name="repeatInterval" value="5000" />  
   <property name="startDelay" value="1000" />
   <property name="repeatCount" value="5" />
 </bean>  
 
 <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
  <property name="jobDetails">  
    <list>  
      <ref bean="job1job" />
      <ref bean="job2job" />
      <ref bean="job3job" />
      <ref bean="job4job" />  
    </list>  
  </property>  
  <property name="triggers">  
    <list>  
      <ref bean="simpleTrigger1" />
      <ref bean="simpleTrigger2" />
      <ref bean="simpleTrigger3" />
      <ref bean="simpleTrigger4" />  
    </list>  
  </property>  
 </bean>
</beans>
package org.eko.jobs;

import java.util.Date;

import org.eko.BusinessJobs.Job1;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;


@Component
@DisallowConcurrentExecution
public class BusinessJobA extends QuartzJobBean
{
	public static int REPEATINTERVALINMILLISECONDS=2000;
	public static int REPEATCOUNT=20;
	
	Job1 job1=new Job1();

	@Override
	protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
		
		SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
		
		String name = arg0.getMergedJobDataMap().getString("name");
        System.out.println("[" + new Date() + "] Hello from Quartz! " + name);
		
		System.out.println("Executing Business Object A");
		try
		{
			job1.doPerform();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}
package org.eko.BusinessJobs;

import java.util.List;

import org.eko.entity.SimpliJob;
import org.eko.repository.SimpliJobRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

@Service
public class Job1 {

	@Autowired
	private SimpliJobRepository simpliJobRepository;
	
	public void doPerform()
	{
		System.out.println("\nJob1 Performing");
		
		Sort sortID=new Sort(new Sort.Order(Sort.Direction.DESC,"id"));
		
		List<SimpliJob> jobsDescID=simpliJobRepository.findAll(sortID);
		for (SimpliJob simpliJob : jobsDescID) {
			System.out.println(simpliJob);
		}
		System.out.println("\nJob1 Done\n");
	}
}
package org.eko.controller;

import java.util.Calendar;

import org.eko.entity.SimpliJob;
import org.eko.jobs.BusinessJobA;
import org.eko.jobs.BusinessJobB;
import org.eko.jobs.BusinessJobC;
import org.eko.jobs.BusinessJobD;
import org.eko.repository.SimpliJobRepository;
import org.eko.service.InitDbService;
import org.quartz.DateBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class QuartzSchedulerController {
	
	JobDetail jobDetail1;
	JobDetail jobDetail2;
	JobDetail jobDetail3;
	JobDetail jobDetail4;
	Trigger trigger1;
	Trigger trigger2;
	Trigger trigger3;
	Trigger trigger4;
	Scheduler scheduler;
	
	@Autowired
	private SimpliJobRepository simpliJobRepository;
	
	public void scheduleJob(SimpliJob simpliJob) throws SchedulerException
	{
		scheduler=new StdSchedulerFactory().getScheduler();
		if(simpliJob.getStatus()==1){
		if(simpliJob.getId()==1)
		{
			jobDetail1=JobBuilder.newJob(BusinessJobA.class).withIdentity(simpliJob.getName(),simpliJob.getSimpliGroup()).build();
			trigger1=(Trigger) TriggerBuilder.newTrigger().withIdentity("Trigger1",simpliJob.getSimpliGroup()).startAt(DateBuilder.dateOf(simpliJob.getStartTime().get(Calendar.HOUR_OF_DAY), simpliJob.getStartTime().get(Calendar.MINUTE), simpliJob.getStartTime().get(Calendar.SECOND), simpliJob.getStartTime().get(Calendar.DAY_OF_MONTH),simpliJob.getStartTime().get(Calendar.MONTH)+1,simpliJob.getStartTime().get(Calendar.YEAR))).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInMilliseconds(BusinessJobA.REPEATINTERVALINMILLISECONDS).withRepeatCount(BusinessJobA.REPEATCOUNT)).forJob(jobDetail1).build();
			scheduler.scheduleJob(jobDetail1,trigger1);
			System.out.println("BusinessObjectA Scheduled!");
		}
		if(simpliJob.getId()==2)
		{
			jobDetail2=JobBuilder.newJob(BusinessJobB.class).withIdentity(simpliJob.getName(),simpliJob.getSimpliGroup()).build();
			trigger2=(Trigger) TriggerBuilder.newTrigger().withIdentity("Trigger2",simpliJob.getSimpliGroup()).startAt(DateBuilder.dateOf(simpliJob.getStartTime().get(Calendar.HOUR_OF_DAY), simpliJob.getStartTime().get(Calendar.MINUTE), simpliJob.getStartTime().get(Calendar.SECOND), simpliJob.getStartTime().get(Calendar.DAY_OF_MONTH),simpliJob.getStartTime().get(Calendar.MONTH)+1,simpliJob.getStartTime().get(Calendar.YEAR))).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInMilliseconds(BusinessJobB.REPEATINTERVALINMILLISECONDS).withRepeatCount(BusinessJobB.REPEATCOUNT)).forJob(jobDetail2).build();
			scheduler.scheduleJob(jobDetail2,trigger2);
			System.out.println("BusinessObjectB Scheduled!");
		}
		if(simpliJob.getId()==3)
		{
			jobDetail3=JobBuilder.newJob(BusinessJobC.class).withIdentity(simpliJob.getName(),simpliJob.getSimpliGroup()).build();
			trigger3=(Trigger) TriggerBuilder.newTrigger().withIdentity("Trigger3",simpliJob.getSimpliGroup()).startAt(DateBuilder.dateOf(simpliJob.getStartTime().get(Calendar.HOUR_OF_DAY), simpliJob.getStartTime().get(Calendar.MINUTE), simpliJob.getStartTime().get(Calendar.SECOND), simpliJob.getStartTime().get(Calendar.DAY_OF_MONTH),simpliJob.getStartTime().get(Calendar.MONTH)+1,simpliJob.getStartTime().get(Calendar.YEAR))).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInMilliseconds(BusinessJobC.REPEATINTERVALINMILLISECONDS).withRepeatCount(BusinessJobC.REPEATCOUNT)).forJob(jobDetail3).build();
			scheduler.scheduleJob(jobDetail3,trigger3);
			System.out.println("BusinessObjectC Scheduled!");
		}
		if(simpliJob.getId()==4)
		{
			jobDetail4=JobBuilder.newJob(BusinessJobD.class).withIdentity(simpliJob.getName(),simpliJob.getSimpliGroup()).build();
			trigger4=(Trigger) TriggerBuilder.newTrigger().withIdentity("Trigger4",simpliJob.getSimpliGroup()).startAt(DateBuilder.dateOf(simpliJob.getStartTime().get(Calendar.HOUR_OF_DAY), simpliJob.getStartTime().get(Calendar.MINUTE), simpliJob.getStartTime().get(Calendar.SECOND), simpliJob.getStartTime().get(Calendar.DAY_OF_MONTH),simpliJob.getStartTime().get(Calendar.MONTH)+1,simpliJob.getStartTime().get(Calendar.YEAR))).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInMilliseconds(BusinessJobD.REPEATINTERVALINMILLISECONDS).withRepeatCount(BusinessJobD.REPEATCOUNT)).forJob(jobDetail4).build();
			scheduler.scheduleJob(jobDetail4,trigger4);
			System.out.println("BusinessObjectD Scheduled!");
		}
		simpliJob.setStatus(2);
		simpliJobRepository.save(simpliJob);
		}
		else
		{
			System.err.println("Job Already Scheduled!");
		}
		scheduler.start();
	}
	
	public void unscheduleJob(SimpliJob simpliJob) throws SchedulerException
	{
		if(simpliJob.getStatus()==2){
		if(simpliJob.getId()==1)
		{
			scheduler.unscheduleJob(trigger1.getKey());
			System.out.println("BusinessObjectA descheduled!");
		}
		if(simpliJob.getId()==2)
		{
			scheduler.unscheduleJob(trigger2.getKey());
			System.out.println("BusinessObjectB descheduled!");
		}
		if(simpliJob.getId()==3)
		{
			scheduler.unscheduleJob(trigger3.getKey());
			System.out.println("BusinessObjectC descheduled!");
		}
		if(simpliJob.getId()==4)
		{
			scheduler.unscheduleJob(trigger4.getKey());
			System.out.println("BusinessObjectD descheduled!");
		}
		simpliJob.setStatus(1);
		simpliJobRepository.save(simpliJob);
		}
		else
		{
			System.err.println("Job Not Scheduled!");
		}
	}
}

共有1个答案

郎鹤龄
2023-03-14

您正在手动创建作业bean,而不是注入它。以下是您应该如何做到这一点:

@Component
@DisallowConcurrentExecution
public class BusinessJobA extends QuartzJobBean
{

    @Autowired
    private Job1 job1;

    /* ... */

}

此外,创建职务数据时不设置任何职务数据,请尝试使用如下所示:

JobBuilder
    .newJob(BusinessJobD.class)
    .withIdentity(simpliJob.getName(),simpliJob.getSimpliGroup())
    .usingJobData("name", "some name")
    .build();
 类似资料:
  • 我正在使用开发一个Spring Boot项目,最近我添加了来为每个请求添加traceId。但是,当作业被系统自动触发时,它不能像在控制器或服务中调用action时那样传播traceId。我是否必须自定义sleuth日志记录或其他东西来将traceId传播到其他服务? 示例:当我通常调用controller时,sleuth工作良好,并且我已经将traceId传播到其他服务 但是,当我的作业被自动触发

  • 我使用的是spring boot,我有一个从数据库中存储/检索一些数据的服务。我想使用一个石英工作使用我的服务。我从网上尝试了很多建议,想把石英和spring boot整合起来,但都不奏效。 这是我的代码: 1)我添加了org.quartz-scheduler作为pom.xml中的依赖项: 2)这是我的应用程序。配置为将mysql用作我的服务的数据库的属性: 3)这是我的服务: 4)调度程序类:

  • Spring使用Quartz的顺序作业计划 我有三个或更多的工作,这取决于他们各自以前的工作,他们将按顺序运行。如果完成运行,当完成运行。如果在上一个中发生任何错误,则不会激发下一个触发的作业。我试图了解工作链使用石英,但无法通过它。 作业顺序如下所示 提前谢了。

  • 我在grails中使用服务,并从控制器中的服务获取和设置数据,没有问题。我知道如何使用它。。。但是这个问题我解决不了,如果你知道出了什么问题,请帮助我。 有一个QuartzWork,我从控制器的服务时间表...数据存储在PostgreSQL中。使用所有插件和2.3.3 Grails的最新版本。在下面的代码中,我只想打印昵称,但我无法获得服务。试图得到豆,def grailsApplication但

  • : 是一个从Hibernate获取数据的经典Spring服务。正如我上面所说的,在我搬到Spring Boot之前,这一直很有效。 当我用经典的Spring应用程序实现这段代码时,完成了对服务的自动化操作。