spring task定时任务调用一个短信的发送接口总是报空指针异常

2016-06-30 17:48:30,321 ERROR [org.springframework.scheduling.support.TaskUtils$LoggingErrorHandler] - Unexpected error occurred in scheduled task.
java.lang.NullPointerException
at com.pactera.jeesite.modules.soa.service.impl.MessageApplicationImpl.sendMsgByTelphones(MessageApplicationImpl.java:50)
at com.pactera.jeesite.modules.jobTask.MyJob.sendMsgByMidFlights(MyJob.java:105)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:178)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:292)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
![![图片说明](https://img-ask.csdn.net/upload/201606/30/1467282244_481450.png)图片说明](https://img-ask.csdn.net/upload/201606/30/1467282236_43015.png)图片说明

3个回答

跟你一样的问题 在本地没事 放服务器就这样了

lrr19930405
天籁知世 解决了吗?我也遇到这样的问题了
2 年多之前 回复

图片说明

图片说明

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Spring 定时任务 在执行方法时报空指针

定时任务的xml: <bean id="autoIPV6BusinessAlarmStatisticsJob" class="org.springframework.scheduling.quartz.JobDetailBean"> <property name="jobClass"> <value>com.boco.auto.AutoIPV6BusinessAlarmStatisticsReport</value> </property> </bean> <bean id="autoIPV6BusinessAlarmStatistics" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail"> <ref local="autoIPV6BusinessAlarmStatisticsJob" /> </property> <property name="cronExpression"> <value>0 30 3 * * ?</value> </property> </bean> Spring注入: <bean name="/ReportCommonActionPipeRes" class="com.boco.web.struts.action.report.ReportCommonActionPipeRes" parent="baseAction"> <property name="reportCommonDao"> <ref local="reportCommonDao" /> </property> <property name="reportCommonDao_Local"> <ref local="reportCommonDao_Local" /> </property> <property name="reportCommonGroupDao"> <ref local="reportCommonGroupDao" /> </property> <property name="reportCommonService"> <ref local="reportCommonService" /> </property> <property name="linkReportDao_Local"> <ref local="linkReportDao_Local" /> </property> <property name="mysqlBaseDao"> <ref bean="mysqlBaseService" /> </property> <property name="statementManagementBean"> <ref bean="statementManagementBean" /> </property> <!-- add liuhuipeng --> <property name="vendorfaultService"> <ref local="vendorfaultService" /> </property> </bean> <bean id="vendorfaultService" class="com.boco.alarm.service.impl.VendorFaultReportServiceImpl"> <property name="reportCommonDao"> <ref local="reportCommonDao"/> </property> <property name="reportCommonDao_Local"> <ref local="reportCommonDao_Local" /> </property> <property name="alarmReportDao"> <ref local="alarmReportDao" /> </property> <property name="statementManagementBean"> <ref bean="statementManagementBean" /> </property> </bean> 定时任务: public class AutoAlarmStatisticsReport implements Job{ static Logger logger = Logger.getLogger(AutoAlarmStatisticsReport.class) ; private ReportCommonActionPipeRes pipeResAction; @Override public void execute(JobExecutionContext arg0) throws JobExecutionException { logger.info("+++进入定时任务。+++"); generateReport(); } public void generateReport(){ logger.info("modelName=AlarmStatistics"); pipeResAction = (ReportCommonActionPipeRes)StartupApp.getInstance(). getAppContext().getBean("reportpiperesource"); String modelName = "IPV6BusinessAlarmStatistics"; Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String today = sdf.format(date); this.pipeResAction.insertBusinessNEStatistics(modelName); //insertBusinessNEStatistics(modelName); } } 调用此方法: public boolean insertBusinessNEStatistics(String modelName){ boolean isOk = false; Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String createDate = sdf.format(date); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date datestart = new Date(); String startDateString=""; startDateString= sdf1.format(datestart); List<Map> Allist = new ArrayList(); String informixSql = statementManagementBean.getStatementByName(modelName.trim()); Map parameterMap = new HashMap(); if((null == informixSql)||informixSql.equalsIgnoreCase("no such table")){ return isOk; }else{ String[] sql_Array = informixSql.split(";"); List<Map> dataList = new ArrayList<Map>(); for(String sql : sql_Array){ if(sql != null && sql.trim().length() > 0){ if(modelName.equalsIgnoreCase("AlarmStatistics")){ String procName = "{call pro_alarm_trans_counteveryday()}"; boolean isInsertflag= false; //测试: isInsertflag = true; // try { // isInsertflag = vendorfaultService.insertIPV6AlarmCount(procName); // logger.info("++获得告警标识:++"+isInsertflag); // } catch (Exception e) { // TODO: handle exception // logger.error("error 错误的信息", e); // } if(isInsertflag == true){ try{ dataList = vendorfaultService.queyAlarm(parameterMap, sql.trim(), false); }catch(Throwable t){ logger.error("error 错误的信息", t); } }else{ return isInsertflag; } }else{ //dataList = reportCommonDao.commonQuery(sql.trim(), parameterMap); dataList = reportCommonDao.commonQuery(sql.trim(), parameterMap); } } } isOk = true; } return isOk; }

spring task中怎么启动带参数的方法

<task:scheduled ref="testService" method="sayHello" cron="3/11 * * * * ?" /> 就像这样, 加入sayHello带有参数怎么写 加入带有 user实体参数 user已经被spring容器管理

spring 定时任务延迟执行原因

设置的每5秒执行一次,实际上并不是按照设置的时间间隔执行 ``` //代码 @Scheduled(cron = "${scheduled.cron}") public void test() { System.out.println("我开始执行啦" + new Date()); } // 执行结果 我开始执行啦Wed Apr 03 17:14:33 CST 2019 我开始执行啦Wed Apr 03 17:15:29 CST 2019 我开始执行啦Wed Apr 03 17:15:31 CST 2019 我开始执行啦Wed Apr 03 17:16:27 CST 2019 我开始执行啦Wed Apr 03 17:17:25 CST 2019 我开始执行啦Wed Apr 03 17:18:24 CST 2019 我开始执行啦Wed Apr 03 17:18:26 CST 2019 ```

使用spring taskScheduler实现动态任务管理

求教各位,怎么使用spring taskScheduler实现动态任务管理,公司规定不用Quartz 这个框架,有这方面经验的大牛吗?

Java中使用quartz定时器:定时处理类中却不能注入jdbc的接口类,报空指针

定时器配置文件: <?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:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 使用MethodInvokingJobDetailFactoryBean,任务类可以不实现Job接口,通过targetMethod指定调用方法--> <bean id="cathodicInspectTaskJob" class="com.geok.gas.CathodicInspectTimer"/> <bean id="cathodicInspectJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <!--false表示等上一个任务执行完后再开启新的任务--> <property name="concurrent" value="false"/> <property name="targetObject"> <ref bean="cathodicInspectTaskJob"/> </property> <property name="targetMethod"> <value>run</value> </property> </bean> <!-- 调度触发器 --> <bean id="cathodicInspectTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <property name="jobDetail"> <ref bean="cathodicInspectJob" /> </property> <property name="cronExpression"> <value> 0 39 09 * * ? </value> </property> </bean> <!-- 调度工厂 --> <bean id="scheduler2" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="cathodicInspectTrigger"/> </list> </property> </bean> </beans> ``` ``` 处理类:CathodicInspectTimer package com.geok.gas; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import com.geok.core.common.exception.GeoException; import com.geok.core.common.util.DateTime; import com.geok.core.common.util.PIMConfig; import com.geok.core.jdbc.def.IJdbcDao; import com.geok.system.common.OrgUtil; import com.project.web.util.UUID; public class CathodicInspectTimer { @Autowired private IJdbcDao jdbcDao; private String table_name =PIMConfig.DATABASE_OWNERBY+"pi";//阴保检测工作表(要插入数据的表) private String PC_USER_MENU =PIMConfig.DATABASE_OWNERBY+"PC_USER_MENU";//用户菜单表 private String PC_USER =PIMConfig.DATABASE_OWNERBY+"PC_USER";//系统用户表 String time=DateTime.getDateTime();//系统日期和时间,格式: yyyy-MM-dd HH:mm:ss String yearMonth=DateTime.getYearMonth();//系统当前年月,格式: yyyy-MM public void run(){ System.out.println("阴保作业任务开始 running!"); insertData(); } @SuppressWarnings("rawtypes") private void insertData(){ try { long start = System.currentTimeMillis();//运行起始时间 List personList = this.getPersonList();//获取系统用户数据 Map<String,Map> personMap = new HashMap<String, Map>();//以数据的id为key,数据本身为map的map对象 for(int i=0;i<personList.size();i++){ Map map = (Map)personList.get(i); personMap.put(map.get("EVENTID").toString(), map); } List list=this.getPersonData("010202020108");//阴保测试作业有新增权限的数据集合 String sqlinsert = "INSERT INTO "+table_name+" (EVENTID, DEPARTMENTID, CREATEID, CREATENAME, CREATEDATE, MODIFYID, MODIFYNAME, MODIFYDATE,WORKNAME)";//要插入的列 OrgUtil util = new OrgUtil();//部门工具类 for(int j=0;j<list.size();j++){//循环拼接sql语句来添加数据 Map map1 = (Map)list.get(j); String USEREVENTID = (String)map1.get("USEREVENTID");//获取有权限的用户id Map map2 = personMap.get(USEREVENTID);//通过用户id获取该用户对象 sqlinsert += " select '"+UUID.getUUID()+"','"+map2.get("ORGID")+"','" +map2.get("EVENTID")+"','"+map2.get("NAME")+"','"+time+"','" +map2.get("EVENTID")+"','"+map2.get("NAME")+"','"+time+"','" +yearMonth.replace("-", "年")+"月"+util.getOrgName(map2.get("ORGID").toString())+"阴保检测作业'" +" FROM DUAL UNION "; } if(sqlinsert.indexOf("UNION")>0){//判断数据集合中存在数据 sqlinsert = sqlinsert.substring(0, sqlinsert.length()-6); jdbcDao.insertOrUpdate(sqlinsert); } long end = System.currentTimeMillis();//运行结束时间 System.out.println("插入:"+list.size()+"条 "+ (end - start) + "毫秒"); System.out.println("阴保作业任务结束 running!"); } catch (Exception e) { e.printStackTrace(); } } private List getPersonData(String menuId) throws GeoException{ String sql = "SELECT * FROM "+PC_USER_MENU+" T WHERE T.MENUID = '"+menuId+"'"; return jdbcDao.queryForMapList(sql); } /** * 获取系统用户数据 * @return * @throws GeoException */ private List getPersonList() throws GeoException{ String sql = "SELECT T.EVENTID,T.NAME,T.ORGID FROM "+PC_USER+" T WHERE T.ACTIVE = 1"; return jdbcDao.queryForMapList(sql); } } ``` ```

Spring 定时任务执行时有异常

Spring定时任务,时不时会爆出这么个异常,请大神解释下是什么原因 2015-12-30 16:00:00,123 ERROR [org.quartz.core.JobRunShell] - <Job DEFAULT.runAddTbCdqResultfourJob threw an unhandled Exception: > org.springframework.scheduling.quartz.JobMethodInvocationFailedException: Invocation of method 'addTbCdqResultfour' on target class [class com.wind.connector.quartz.RunAddTbCdqResultfour] failed; nested exception is org.hibernate.NonUniqueResultException: query did not return a unique result: 2 at org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean$MethodInvokingJob.executeInternal(MethodInvokingJobDetailFactoryBean.java:269) at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:86) at org.quartz.core.JobRunShell.run(JobRunShell.java:202) at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:525) Caused by: org.hibernate.NonUniqueResultException: query did not return a unique result: 2 at org.hibernate.impl.AbstractQueryImpl.uniqueElement(AbstractQueryImpl.java:844) at org.hibernate.impl.AbstractQueryImpl.uniqueResult(AbstractQueryImpl.java:835) at com.wind.daoImpl.BaseDaoImpl.uniqueQuery(BaseDaoImpl.java:46) at com.wind.daoImpl.TbCdqResultfourDaoImpl.getCdqResultByBeginDate(TbCdqResultfourDaoImpl.java:68) at com.wind.managerImpl.TbConnectorManagerImpl.addTbCdqResultfour(TbConnectorManagerImpl.java:424) at com.wind.managerImpl.TbConnectorManagerImpl$$FastClassByCGLIB$$dd5fd868.invoke(<generated>) at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:149) at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:700) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:635) at com.wind.managerImpl.TbConnectorManagerImpl$$EnhancerByCGLIB$$24d2f90f.addTbCdqResultfour(<generated>) at com.wind.connector.quartz.RunAddTbCdqResultfour.addTbCdqResultfour(RunAddTbCdqResultfour.java:58) at sun.reflect.GeneratedMethodAccessor185.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.util.MethodInvoker.invoke(MethodInvoker.java:276) at org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean$MethodInvokingJob.executeInternal(MethodInvokingJobDetailFactoryBean.java:260) ... 3 more 2015-12-30 16:00:00,124 ERROR [org.quartz.core.ErrorLogger] - <Job (DEFAULT.runAddTbCdqResultfourJob threw an exception.> org.quartz.SchedulerException: Job threw an unhandled exception. [See nested exception: org.springframework.scheduling.quartz.JobMethodInvocationFailedException: Invocation of method 'addTbCdqResultfour' on target class [class com.wind.connector.quartz.RunAddTbCdqResultfour] failed; nested exception is org.hibernate.NonUniqueResultException: query did not return a unique result: 2] at org.quartz.core.JobRunShell.run(JobRunShell.java:213) at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:525) Caused by: org.springframework.scheduling.quartz.JobMethodInvocationFailedException: Invocation of method 'addTbCdqResultfour' on target class [class com.wind.connector.quartz.RunAddTbCdqResultfour] failed; nested exception is org.hibernate.NonUniqueResultException: query did not return a unique result: 2 at org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean$MethodInvokingJob.executeInternal(MethodInvokingJobDetailFactoryBean.java:269) at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:86) at org.quartz.core.JobRunShell.run(JobRunShell.java:202) ... 1 more Caused by: org.hibernate.NonUniqueResultException: query did not return a unique result: 2 at org.hibernate.impl.AbstractQueryImpl.uniqueElement(AbstractQueryImpl.java:844) at org.hibernate.impl.AbstractQueryImpl.uniqueResult(AbstractQueryImpl.java:835) at com.wind.daoImpl.BaseDaoImpl.uniqueQuery(BaseDaoImpl.java:46) at com.wind.daoImpl.TbCdqResultfourDaoImpl.getCdqResultByBeginDate(TbCdqResultfourDaoImpl.java:68) at com.wind.managerImpl.TbConnectorManagerImpl.addTbCdqResultfour(TbConnectorManagerImpl.java:424) at com.wind.managerImpl.TbConnectorManagerImpl$$FastClassByCGLIB$$dd5fd868.invoke(<generated>) at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:149) at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:700) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:635) at com.wind.managerImpl.TbConnectorManagerImpl$$EnhancerByCGLIB$$24d2f90f.addTbCdqResultfour(<generated>) at com.wind.connector.quartz.RunAddTbCdqResultfour.addTbCdqResultfour(RunAddTbCdqResultfour.java:58) at sun.reflect.GeneratedMethodAccessor185.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.util.MethodInvoker.invoke(MethodInvoker.java:276) at org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean$MethodInvokingJob.executeInternal(MethodInvokingJobDetailFactoryBean.java:260) ... 3 more

spring任务调度方法重复执行2次

如题: 在使用spring任务调度时,任务的方法设置成每隔4个小时执行一次,但是现在发现这个方法在每隔4个小时执行了2次,看图。![图片说明](https://img-ask.csdn.net/upload/201603/07/1457321861_529420.png) ![spring的配置](https://img-ask.csdn.net/upload/201603/07/1457321893_428075.png) ![方法](https://img-ask.csdn.net/upload/201603/07/1457321947_33247.png)

quartz 定时任务被挂起问题

场景: 一个quartz定时任务,定时调用一个方法,方法里面通过多数据源从三个数据源ds1, ds2, ds3,获取数据,然后将这批数据插入另一个数据源 ds4的表中,再将这批数据从 ds4中查出来进行业务分析, 用的c3p0 连接池, 报错:【下面有贴出来】 同时 数据源 ds1 数据库出现异常, 报错后,数据源 ds1, ds2, ds3 的数据不能同步到 ds4 了,ds4的业务也不在执行,定时任务被挂起.. 这种场景 有可能是什么原因 引起定时任务被挂起的啊? WARN [com.mchange.v2.async.ThreadPoolAsynchronousRunner] - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@3ee2b918 -- APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tasks! [com.mchange.v2.async.ThreadPoolAsynchronousRunner] - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@3ee2b918 -- APPARENT DEADLOCK!!! Complete Status: Managed Threads: 3 Active Threads: 3 Active Tasks: com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@16e5f6e9 (com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#0) com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@53b546bd (com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#2) com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@22374d3a (com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#1) Pending Tasks: com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask@5caf2c62 com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@708b0577 com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@3714015a Pool thread stack traces: Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#0,5,main] java.net.SocketInputStream.socketRead0(Native Method) java.net.SocketInputStream.read(SocketInputStream.java:129) oracle.net.ns.Packet.receive(Unknown Source) oracle.net.ns.DataPacket.receive(Unknown Source) oracle.net.ns.NetInputStream.getNextPacket(Unknown Source) oracle.net.ns.NetInputStream.read(Unknown Source) oracle.net.ns.NetInputStream.read(Unknown Source) oracle.net.ns.NetInputStream.read(Unknown Source) oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1099) oracle.jdbc.driver.T4CMAREngine.unmarshalSB1(T4CMAREngine.java:1070) oracle.jdbc.driver.T4C7Ocommoncall.receive(T4C7Ocommoncall.java:106) oracle.jdbc.driver.T4CConnection.logoff(T4CConnection.java:489) oracle.jdbc.driver.PhysicalConnection.close(PhysicalConnection.java:1446) com.mchange.v2.c3p0.impl.NewPooledConnection.close(NewPooledConnection.java:549) com.mchange.v2.c3p0.impl.NewPooledConnection.close(NewPooledConnection.java:234) com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.destroyResource(C3P0PooledConnectionPool.java:470) com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask.run(BasicResourcePool.java:964) com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547) Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#2,5,main] java.net.SocketInputStream.socketRead0(Native Method) java.net.SocketInputStream.read(SocketInputStream.java:129) oracle.net.ns.Packet.receive(Unknown Source) oracle.net.ns.DataPacket.receive(Unknown Source) oracle.net.ns.NetInputStream.getNextPacket(Unknown Source) oracle.net.ns.NetInputStream.read(Unknown Source) oracle.net.ns.NetInputStream.read(Unknown Source) oracle.net.ns.NetInputStream.read(Unknown Source) oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1099) oracle.jdbc.driver.T4CMAREngine.unmarshalSB1(T4CMAREngine.java:1070) oracle.jdbc.driver.T4C7Ocommoncall.receive(T4C7Ocommoncall.java:106) oracle.jdbc.driver.T4CConnection.logoff(T4CConnection.java:489) oracle.jdbc.driver.PhysicalConnection.close(PhysicalConnection.java:1446) com.mchange.v2.c3p0.impl.NewPooledConnection.close(NewPooledConnection.java:549) com.mchange.v2.c3p0.impl.NewPooledConnection.close(NewPooledConnection.java:234) com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.destroyResource(C3P0PooledConnectionPool.java:470) com.mchange.v2.resourcepool.BasicResourcePool$1DestroyResourceTask.run(BasicResourcePool.java:964) com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547) Thread[com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#1,5,main] java.net.SocketInputStream.socketRead0(Native Method) java.net.SocketInputStream.read(SocketInputStream.java:129) oracle.net.ns.Packet.receive(Unknown Source) oracle.net.ns.NSProtocol.connect(Unknown Source) oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1023) oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:282) oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:447) oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165) oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35) oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:839) com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:134) com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182) com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171) com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137) com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014) com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32) com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810) com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunn

在java timer定时器中调用dao层会报错

现在在做一个web项目,使用spring+springMVC+hibernate框架, 问题描述: 项目中有一个扫描的功能,分即时任务、定时任务、周期任务三种,即时任务已经实现了,现在使用java.util.Timer、java.util.TimerTask类做定时任务,重写TimerTask的run方法,在run方法中调用之前已经没有问题的即时任务扫描方法。每次运行定时任务时,会卡在dao层方法的调用上,因为在即时任务的扫描方法中调用了dao层的数据操作方法,报错“No Session found for current thread”。 即时任务的执行流程:前台提交即时任务扫描请求->控制器调用service层的立即扫描方法startImmediateTask(); 定时任务的执行流程:前台提交定时任务扫描请求->控制器调用service层的定时扫描方法startTimerTask()->调用立即扫描方法startImmediateTask()。 下面附上代码和配置文件,请各位大牛帮忙解决啊! service层代码 ```java /** * 开始定时扫描任务 * @param blTask */ public void startTimerTask(final BLTask blTask) { Date startDate = blTask.getStartTime(); TimerTask task = new TimerTask() { @Override public void run() { // 调用扫描方法 startImmediateTask(blTask); } }; Timer timer = new Timer(); timer.schedule(task, startDate); } /** * 开始即时扫描任务 * @param blTask */ public void startImmediateTask(BLTask blTask) { BLScanParam blScanParam = new BLScanParam(); BLPolicyGroup blPolicyGroup = null; // 策略组 List<BLCheckItem> blCheckItems = null; // 检查项 Map<Long, BLCheckScript> blCheckScriptMap = new HashMap<Long, BLCheckScript>(); // 检查脚本 Long pgId = null; // 策略组ID String alias = null; // 策略别名、检查项别名 Long osType = blTask.getOsType(); // 操作系统类型 List<Long> csIds = new ArrayList<Long>(); // 检查脚本ID数组 blScanParam.setBlTask(blTask); pgId = blTask.getPgId(); // 通过策略组ID查找策略组 blPolicyGroup = blPolicyGroupDao.get(pgId); if (blPolicyGroup == null) { return; } blScanParam.setBlPolicyGroup(blPolicyGroup); alias = blPolicyGroup.getAlias(); // 通过别名、操作系统类别查找所有匹配的检查项 blCheckItems = blCheckItemDao.queryByProerties(new String[]{"alias", "osType"}, new Object[]{alias, osType}); if (blCheckItems == null || blCheckItems.size() <= 0) { return; } blScanParam.setBlCheckItems(blCheckItems); for (BLCheckItem blCheckItem : blCheckItems) { csIds.add(blCheckItem.getCsId()); } int size = csIds.size(); // 获取当前策略组下的所有检查项的检测脚本 List<BLCheckScript> blCheckScripts = blCheckScriptDao.queryByProerties("csId", (Long[])csIds.toArray(new Long[size])); for (BLCheckScript blCheckScript : blCheckScripts) { // 获取当前策略组下的所有检测脚本,并放入map中 blCheckScriptMap.put(blCheckScript.getCsId(), blCheckScript); } blScanParam.setBlCheckScriptMap(blCheckScriptMap); // 分割ip为数组,传入TaskDispatch String[] ips = getIps(blTask.getIpArea()); TaskDispatch taskDispatch = new TaskDispatch(ips, blScanParam); taskDispatch.StartTask(); // 将当前TaskDispatch对象的引用放入taskDispatchMap中,供停止任务时使用 taskDispatchMap.put(blTask.getTkId(), taskDispatch); } ``` BaseDao的部分代码 ```java public class BaseDao<E> implements Dao<E> { public SessionFactory getSessionFactory() { return this.sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Session getSession() { return this.sessionFactory.getCurrentSession(); } @Resource(name = "sessionFactory") public void setSF(SessionFactory sessionFactory) { setSessionFactory(sessionFactory); } } ``` applicationContext.xml ```xml <?xml version="1.0" encoding="UTF-8"?> <context:annotation-config /> <context:component-scan base-package="com.djbh" /> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="com.mysql.jdbc.Driver" /> <property name="jdbcUrl" value="jdbc:mysql://192.168.1.247:3306/djbh_db?useUnicode=true&amp;characterEncoding=utf-8" /> <property name="user" value="root" /> <property name="password" value="mysql" /> <!-- <property name="driverClass" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" /> <property name="jdbcUrl" value="jdbc:sqlserver://localhost:1433;DatabaseName=DJBH_DB" /> <property name="user" value="sa" /> <property name="password" value="123456" /> --> <property name="acquireIncrement" value="3" /> <property name="idleConnectionTestPeriod" value="120" /> <property name="initialPoolSize" value="3" /> <property name="minPoolSize" value="3" /> <property name="maxPoolSize" value="15" /> <property name="numHelperThreads" value="3" /> <property name="preferredTestQuery" value="select 1" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> <!-- <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop> --> <!-- <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop> --> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.use_outer_join">true</prop> <prop key="hibernate.jdbc.fetch_size">30</prop> <prop key="hibernate.jdbc.batch_size">30</prop> <prop key="hibernate.jdbc.batch_versioned_data">true</prop> <prop key="hibernate.cache.use_second_level_cache">true</prop> <prop key="hibernate.cache.use_query_cache">true</prop> <prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</prop> <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop> <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="javax.persistence.validation.mode">none</prop> </props> </property> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan"> <list> <value>com.djbh.model</value> </list> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 启动对@AspectJ注解的支持 --> <aop:aspectj-autoproxy/> </beans> ``` springmvc-servlet.xml ```xml <?xml version="1.0" encoding="UTF-8"?> <mvc:annotation-driven/> <mvc:resources location="/static/" mapping="/static/**"/> <mvc:resources location="/attachment/report_html/" mapping="/attachment/report_html/**"/> <context:component-scan base-package="com.djbh.controller" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass"><value>org.springframework.web.servlet.view.JstlView</value></property> <property name="prefix"><value>/WEB-INF/page/</value></property> <property name="suffix"><value>.jsp</value></property> </bean> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="messages" /> <property name="useCodeAsDefaultMessage" value="true" /> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--<property name="maxUploadSize" value="10485760"></property> --> </bean> <aop:aspectj-autoproxy proxy-target-class="true" /> </beans> ``` web.xml ```xml <?xml version="1.0" encoding="UTF-8"?> <display-name>djbh</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:applicationContext*.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>core.web.SystemInitListener</listener-class> </listener> <filter> <filter-name>loginFilter</filter-name> <filter-class>core.web.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>loginFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>characterEncoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> </web-app> ```

java继承TimerTask,定时任务执行一段时间后自动停止

定时配置 ![图片说明](https://img-ask.csdn.net/upload/201710/23/1508728239_250669.png) 定时任务 ![图片说明](https://img-ask.csdn.net/upload/201710/23/1508728254_52174.png) 方法调用 ![图片说明](https://img-ask.csdn.net/upload/201710/23/1508728266_302667.png) 大家帮忙看一下,问题出在哪里

SPRING @Scheduled 定时任没执行

项目主要配置及代码如下,但是启动服务后,一直没执行这个方法,不知什么原因。请指点 package com.yl.reqPos; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.context.annotation.Lazy; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component @Lazy(false) public class Singer { @Scheduled(cron ="0/5 * * * * *") //第二种方式 public void singing(){ Date date=new Date(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); System.out.println(sdf.format(date)); } } applicationContext-jobs.xml配置: <?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:task="http://www.springframework.org/schema/task" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd" default-lazy-init="false"> <context:component-scan base-package="com.yl.reqPos.*" /> <task:scheduler id="scheduler" pool-size="10" /> <task:executor id="executor" keep-alive="3600" pool-size="100-200" queue-capacity="500" rejection-policy="CALLER_RUNS" /> <task:annotation-driven executor="executor" scheduler="scheduler" /> </beans>

timer定时器在项目初始化的时候注入service为null

定时器任务开始执行的时候,一直没办法加载,后来发现是service为null 这是定时器执行的方法,在调用TimeWorkAction以后,里面的service就是null了 ``` public class WorkTimer extends HttpServlet{ //时间间隔(一天) private static final long PERIOD_DAY = 24 * 60 * 60 * 1000; @Override public void init() throws ServletException { // TODO Auto-generated method stub System.out.println("开始执行定时器查询"); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 19); //夜晚23点 calendar.set(Calendar.MINUTE, 57); calendar.set(Calendar.SECOND, 0); Date date=calendar.getTime(); //第一次执行定时任务的时间 TimerTask task = new TimeWorkAction(); Timer timer = new Timer(); timer.schedule(task,date, PERIOD_DAY); super.init(); } } ``` ``` @Component public class TimeWorkAction extends TimerTask{ WorkService workService = (WorkService)ApplicationContextUtil.getBean("workService"); Work work = (Work)ApplicationContextUtil.getBean("work"); public void run(){ try { //获取当前日期 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date1 = new Date(); String dates = simpleDateFormat.format(date1); long currentDate = 0; try { currentDate = simpleDateFormat.parse(dates).getTime(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } //获取权限用户 List userName = workService.getName(); for (int i = 0; i < userName.size(); i++) { Object obj = userName.get(i); String name = obj.toString(); List addDate = workService.addDate(name,currentDate); if(addDate.isEmpty()){ work = new Work(); work.setName(name); work.setWorkDate(currentDate); workService.save(work); } } } catch (Exception e) { e.printStackTrace(); } } public WorkService getWorkService() { return workService; } public void setWorkService(WorkService workService) { this.workService = workService; } public Work getWork() { return work; } public void setWork(Work work) { this.work = work; } } ``` 之前service直接private WorkService workService也不行

SpringBoot 定时访问外部接口时Tomcat报404错误.

想实现定时(每秒)主动访问一次外部的接口,并读取数据,但是程序在容器中运行时报了HttpClientErrorException$NotFound: 404 null的错误,请问各位是什么问题呢? 启动类中的代码 @SpringBootApplication @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) @MapperScan(value = "com.luchao.springbootmybatis.mapper") @EnableScheduling public class SpringbootMybatisApplication { public static void main(String[] args) { SpringApplication.run(SpringbootMybatisApplication.class, args); } } controller中的代码: @Controller public class ClientLicenseController { @Autowired private RestTemplate restTemplate; @Scheduled(fixedRate = 1000) @ResponseBody public void book() { System.out.println("ok"); String paraStr = "db48e27052f54879b50f3edce4fc19bb"; String strReponse = restTemplate.postForObject("http://localhost:8080/getCpInfo/",paraStr, String.class); } } 控制台的错误日志: 2019-03-13 18:00:20.353 ERROR 772 --- [ scheduling-1] o.s.s.s.TaskUtils$LoggingErrorHandler : Unexpected error occurred in scheduled task. org.springframework.web.client.HttpClientErrorException$NotFound: 404 null at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:85) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:97) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:777) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:735) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:669) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:413) ~[spring-web-5.1.2.RELEASE.jar:5.1.2.RELEASE] at com.luchao.springbootmybatis.controller.ClientLicenseController.book(ClientLicenseController.java:47) ~[classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_77] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_77] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_77] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_77] at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84) ~[spring-context-5.1.2.RELEASE.jar:5.1.2.RELEASE] at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-5.1.2.RELEASE.jar:5.1.2.RELEASE] at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_77] at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) [na:1.8.0_77] at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) [na:1.8.0_77] at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) [na:1.8.0_77] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_77] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_77] at java.lang.Thread.run(Thread.java:745) [na:1.8.0_77]

java 怎么样让代码一天就执行一次,根据时间,前提 不能使用任务调度,来吧大神们

java 怎么样让代码一天就执行一次,根据时间来判断,前提 不能使用任务调度,因为在前端这个页面每三分钟刷新一次,访问的jsp其中有些方法不需要执行,这些方法一天执行一次就可以

spring整合quartz定时任务报错,请大神们解救

web.xml中的配置 <servlet> <servlet-name>spring_mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>spring_mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> applicationContext.xml的配置 <!-- 要调用的工作类 --> <bean id="quartzJob" class="com.QuartzJob"></bean> <!-- 定义调用对象和调用对象的方法 --> <bean id="jobtask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <!-- 调用的类 --> <property name="targetObject"> <ref bean="quartzJob"/> </property> <!-- 调用类中的方法 --> <property name="targetMethod"> <value>work</value> </property> </bean> <!-- 定义触发时间 --> <bean id="doTime" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail"> <ref bean="jobtask"/> </property> <!-- cron表达式 --> <property name="cronExpression"> <value>0 */1 * * * ?</value> </property> </bean> <!-- 总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序 --> <bean id="startQuertz" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="doTime"/> </list> </property> </bean> 工作类的代码 public class QuartzJob { public void work() { System.out.println("Quartz的任务调度!!!"); } } 测试类的代码 public class Main { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //如果配置文件中将startQuertz bean的lazy-init设置为false 则不用实例化 //context.getBean("startQuertz"); } 控制台打印的错误信息 Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'startQuertz' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/quartz/spi/JobFactory Caused by: java.lang.NoClassDefFoundError: org/quartz/spi/JobFactory

struts2+spring +ibatis 中使用quartz问题

struts2+spring +ibatis 中使用quartz问题 在spring中配置好了代码如下: <bean id="limitDaysCompanysService" parent="baseTransactionProxyG4"> <property name="target"> <bean class="org.xtone.mt.service.impl.LimitDaysCompanysServiceImpl"> <property name="g4Dao" ref="g4Dao" /> </bean> </property> </bean> <!-- 定义调用对象和调用对象的方法 --> <bean id="jobtask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <!-- 调用的类 --> <property name="targetObject"> <ref bean="limitDaysCompanysService"/> </property> <!-- 调用类中的方法 --> <property name="targetMethod"> <value>LimitDaysCompanysByClose</value> </property> </bean> <!-- 定义调用对象和调用对象的方法 --> <bean id="jobtask2" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <!-- 调用的类 --> <property name="targetObject"> <ref bean="limitDaysCompanysService"/> </property> <!-- 调用类中的方法 --> <property name="targetMethod"> <value>LimitDaysCompanysByState</value> </property> </bean> <!-- 定义触发时间 --> <bean id="doTime" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="jobtask"/> <!-- run at 00:00 everyday --> <property name="cronExpression" value="0 29 13 * * ?"/> </bean> <!-- 定义触发时间 --> <bean id="doTime2" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="jobtask2"/> <!-- run at 00:00 everyday --> <property name="cronExpression" value="0 29 13 * * ?"/> </bean> <!-- 总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序 --> <bean id="startQuertz" lazy-init="true" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="doTime"/> <ref bean="doTime2"/> </list> </property> </bean> 总管理类中lazy-init设置='false'项目启动,这个可以执行起来。我现在要在页面用按钮来执行控制要启动还是暂停。 struts中如何调用这边的方法才能是我的按钮控制这个?

救急,SpringMVC非Controller类中使用任务列队操作service无法连接数据库?

问题: 在任务列队中使用Service操作数据库报错: ``` org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is java.sql.SQLException: interrupt at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:289) at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:377) at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:461) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673) at com.superior.chalk.service.order.OrderServiceImpl$$EnhancerBySpringCGLIB$$bde940af.queryByOrderNo(<generated>) at com.superior.chalk.task.WxPayNotifyTask.doInvoke(WxPayNotifyTask.java:25) at com.superior.chalk.task.queue.TaskQueueService$1.run(TaskQueueService.java:32) at java.lang.Thread.run(Thread.java:748) at java.util.concurrent.Executors$RunnableAdapter.call$$$capture(Executors.java:511) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java) at java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:266) at java.util.concurrent.FutureTask.run(FutureTask.java) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) Caused by: java.sql.SQLException: interrupt at com.alibaba.druid.pool.DruidDataSource.getConnectionInternal(DruidDataSource.java:1405) at com.alibaba.druid.pool.DruidDataSource.getConnectionDirect(DruidDataSource.java:1248) at com.alibaba.druid.filter.FilterChainImpl.dataSource_connect(FilterChainImpl.java:4619) at com.alibaba.druid.filter.FilterAdapter.dataSource_getConnection(FilterAdapter.java:2745) at com.alibaba.druid.filter.FilterChainImpl.dataSource_connect(FilterChainImpl.java:4615) at com.alibaba.druid.filter.logging.LogFilter.dataSource_getConnection(LogFilter.java:876) at com.alibaba.druid.filter.FilterChainImpl.dataSource_connect(FilterChainImpl.java:4615) at com.alibaba.druid.filter.stat.StatFilter.dataSource_getConnection(StatFilter.java:680) at com.alibaba.druid.filter.FilterChainImpl.dataSource_connect(FilterChainImpl.java:4615) at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:1226) at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:1218) at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:90) at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:246) ... 19 more ``` 调用代码: 1junit test method: ![图片说明](https://img-ask.csdn.net/upload/201910/11/1570785874_571316.png) 2 TaskQueueService ``` @Component public class TaskSerialQueueService { // 日志监控 private static final Logger log = Logger.getLogger(TaskSerialQueueService.class); //任务列队 private final LinkedBlockingDeque<TaskQueueHandler> tasks=new LinkedBlockingDeque<>(); //单线程执行器 private ExecutorService service= Executors.newSingleThreadExecutor(); // 检查服务是否运行 private volatile boolean running = true; //线程状态 private Future<?> serviceThreadStatus = null; @PostConstruct public void init(){ serviceThreadStatus=service.submit(new Thread(new Runnable() { @Override public void run() { while (running){ try{ TaskQueueHandler taskQueueHandler= tasks.take(); if(taskQueueHandler!=null){ try{ taskQueueHandler.doInvoke(); }catch (Exception e){ log.error(taskQueueHandler.getTaskName()+" doInvoke Error!",e.getCause()); } } }catch (InterruptedException e){ running=false; } } } })); } ...... ``` 2 WxPayNotifyTask具体任务执行器 ![图片说明](https://img-ask.csdn.net/upload/201910/11/1570785856_861724.png) 在Junit测试中使用new Thread(new Ruanable(){ 在run中操作service也一样报错。 })

shiro放到异步线程中执行时会报这个错,放到线程外就正常了

shiro放到异步线程中执行时会报这个错,放到线程外就正常了,错误如下 org.apache.shiro.UnavailableSecurityManagerException: No SecurityManager accessible to the calling code, either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton. This is an invalid application configuration. ### Cause: org.apache.shiro.UnavailableSecurityManagerException: No SecurityManager accessible to the calling code, either bound to the org.apache.shiro.util.ThreadContext or as a vm static singleton. This is an invalid application configuration. 代码如下: 出错代码: // 保存日志 //创建异步任务 Task task = new Task() { @Override public void run() { // 封装对象 SpringContextHolder.getBean(IOperationLogService.class).insert(operationLog); } }; // 运行任务 SpringContextHolder.getBean(TaskHelper.class).doTask(task); 正常执行代码: IOperationLogService operationLogService = SpringContextHolder.getBean(IOperationLogService.class); operationLogService.insert(operationLog);

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

我以为我学懂了数据结构,直到看了这个导图才发现,我错了

数据结构与算法思维导图

String s = new String(" a ") 到底产生几个对象?

老生常谈的一个梗,到2020了还在争论,你们一天天的,哎哎哎,我不是针对你一个,我是说在座的各位都是人才! 上图红色的这3个箭头,对于通过new产生一个字符串(”宜春”)时,会先去常量池中查找是否已经有了”宜春”对象,如果没有则在常量池中创建一个此字符串对象,然后堆中再创建一个常量池中此”宜春”对象的拷贝对象。 也就是说准确答案是产生了一个或两个对象,如果常量池中原来没有 ”宜春” ,就是两个。...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

Linux面试题(2020最新版)

文章目录Linux 概述什么是LinuxUnix和Linux有什么区别?什么是 Linux 内核?Linux的基本组件是什么?Linux 的体系结构BASH和DOS之间的基本区别是什么?Linux 开机启动过程?Linux系统缺省的运行级别?Linux 使用的进程间通信方式?Linux 有哪些系统日志文件?Linux系统安装多个桌面环境有帮助吗?什么是交换空间?什么是root帐户什么是LILO?什...

Linux命令学习神器!命令看不懂直接给你解释!

大家都知道,Linux 系统有非常多的命令,而且每个命令又有非常多的用法,想要全部记住所有命令的所有用法,恐怕是一件不可能完成的任务。 一般情况下,我们学习一个命令时,要么直接百度去搜索它的用法,要么就直接用 man 命令去查看守冗长的帮助手册。这两个都可以实现我们的目标,但有没有更简便的方式呢? 答案是必须有的!今天给大家推荐一款有趣而实用学习神器 — kmdr,让你解锁 Linux 学习新姿势...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

史上最全的 python 基础知识汇总篇,没有比这再全面的了,建议收藏

网友们有福了,小编终于把基础篇的内容全部涉略了一遍,这是一篇关于基础知识的汇总的文章,请朋友们收下,不用客气,不过文章篇幅肯能会有点长,耐心阅读吧爬虫(七十)多进程multiproces...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

85后蒋凡:28岁实现财务自由、34岁成为阿里万亿电商帝国双掌门,他的人生底层逻辑是什么?...

蒋凡是何许人也? 2017年12月27日,在入职4年时间里,蒋凡开挂般坐上了淘宝总裁位置。 为此,时任阿里CEO张勇在任命书中力赞: 蒋凡加入阿里,始终保持创业者的冲劲,有敏锐的...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

新一代神器STM32CubeMonitor介绍、下载、安装和使用教程

关注、星标公众号,不错过精彩内容作者:黄工公众号:strongerHuang最近ST官网悄悄新上线了一款比较强大的工具:STM32CubeMonitor V1.0.0。经过我研究和使用之...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

大学一路走来,学习互联网全靠这几个网站,最终拿下了一把offer

大佬原来都是这样炼成的

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

什么时候跳槽,为什么离职,你想好了么?

都是出来打工的,多为自己着想

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

你期望月薪4万,出门右拐,不送,这几个点,你也就是个初级的水平

先来看几个问题通过注解的方式注入依赖对象,介绍一下你知道的几种方式@Autowired和@Resource有何区别说一下@Autowired查找候选者的...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《经典算法案例》01-08:如何使用质数设计扫雷(Minesweeper)游戏

我们都玩过Windows操作系统中的经典游戏扫雷(Minesweeper),如果把质数当作一颗雷,那么,表格中红色的数字哪些是雷(质数)?您能找出多少个呢?文中用列表的方式罗列了10000以内的自然数、质数(素数),6的倍数等,方便大家观察质数的分布规律及特性,以便对算法求解有指导意义。另外,判断质数是初学算法,理解算法重要性的一个非常好的案例。

立即提问
相关内容推荐