spring+hibernate quartz定时任务MethodInvokingJobDetailFactoryBean异常

spring | 2019-09-13 10:02:39

用spring的org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean,实现定时任务

配置如下:

<bean id="DailyTaskQtzJob" class="common.Test">
    </bean>  
    <bean id="DailyTaskQtzJobMethod" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
        <property name="targetObject">  
            <ref bean="DailyTaskQtzJob"/>  
        </property>  
                <property name="targetMethod">  
            <value>work</value>  
        </property>  
    </bean> 
          <bean id="DailyTaskCronTriggerBean" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">  
            <property name="jobDetail" ref="DailyTaskQtzJobMethod"></property>  
            <property name="cronExpression" value="*/5 * * * * ?"></property>
    </bean>  
    <bean id="SpringJobSchedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
        <property name="triggers">  
            <list>   
                <ref bean="DailyTaskCronTriggerBean"/> 
            </list>  
        </property>  
    </bean>

报错信息如下:

Caused by: org.springframework.scheduling.quartz.JobMethodInvocationFailedException: Invocation of method 'work' on target class [class common.Test] failed; nested exception is org.hibernate.HibernateException: No Session found for current thread
        at org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean$MethodInvokingJob.executeInternal(MethodInvokingJobDetailFactoryBean.java:327)
        at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:111)
        at org.quartz.core.JobRunShell.run(JobRunShell.java:207)
        ... 1 more
Caused by: org.hibernate.HibernateException: No Session found for current thread
        at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:106)
        at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:881)
        at repository.entity.EntityRepository.session(EntityRepository.java:62)
        at repository.entity.EntityRepository.findById(EntityRepository.java:81)
        at common.Test.work(Test.java:9)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.util.MethodInvoker.invoke(MethodInvoker.java:273)
        at org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean$MethodInvokingJob.executeInternal(MethodInvokingJobDetailFactoryBean.java:318)
        ... 3 more

解决方法:

是给定时任务代码加上事务,如果是aop配置spring的事务,加上配置切到你的定时代码方法上,如果是注解事务在定时任务执行的方法上加上注解@Transactional就可以了。

登录后即可回复 登录 | 注册
    
关注编程学问公众号