我在Servlet的init()方法中启动了定时器Timer,定时执行任务。
在web.xml中通过load-on-startup让servlet能够自动初始化实例,
并且在该Servlet中重写destory()方法,代码内容是销毁servlet时cancel掉定时器。但是不太清楚这个Servlet实例什么时候被销毁,我的定时器可能需要长时间来运行(间隔以天为单位),我怕因为servlet实例不活动,Servlet容器自动把它销毁而导致定时器被无端关闭,有没有这种隐患呢?
在web.xml中通过load-on-startup让servlet能够自动初始化实例,
并且在该Servlet中重写destory()方法,代码内容是销毁servlet时cancel掉定时器。但是不太清楚这个Servlet实例什么时候被销毁,我的定时器可能需要长时间来运行(间隔以天为单位),我怕因为servlet实例不活动,Servlet容器自动把它销毁而导致定时器被无端关闭,有没有这种隐患呢?
请你复习下servlet的生命周期
-------------------------------------
回复人:killme2008(www.rubyeye.net) ( 一星(中级)) 信誉:96-----------------------------------------说的很清晰了,定时器写在ServletContextListener里。
这样在web服务启动时,就会自动启动此监听器,服务停止监听器就停了,和servlet没关系。
所以,servlet作为一个对象,它要什么时候被销毁那只有天知道,或者只有虚拟机自己知道什么时候销毁了。
前半部分说的还有道理,servlet规范是说servlet的销毁是由容器决定或者容器关闭时销毁
不过就部分实现来说都是一直留在内存中的,所以就楼主的情况就是别瞎担心,
先这样做,过段时间后看看。后半部分扯淡了,java什么时候有销毁方法了?
java没有析构函数不用我说吧,java的垃圾回收算法也并不保证没有引用的对象一定被回收。
而且servlet的销毁不是虚拟机说的算,而是由容器决定,两种情况:容器决定回收servlet占据的内存
,容器关闭
在servlet2.2之前的项目几乎都是这样做,或者你知道有更好的办法。
谢谢各位啦!
spring来帮你完成定时的调度http://www.busmate.com/collection/958/12487.html
1. Loads the servlet class.
2. Creates an instance of the servlet class.
3. Initializes the servlet instance by calling the init method.
Initialization is covered in Initializing a Servlet.
2. Invokes the service method, passing request and response objects. Service
methods are discussed in Writing Service Methods.If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's destroy method. When a servlet container determines that a servlet should be removed from service (for example, when a container wants to reclaim memory resources or when it is being shut down), the container calls the destroy method of the Servlet interface. j2ee1.4规范中的两段话。可见,servlet只会有一个实例,容器可能根据需要去销毁servlet的实例,销毁时间应该是不定的。
但可以确定我的那个Servlet服务器配置内存是很多的,有新资源可用应该就不会销毁旧资源的了。希望能够把容器销毁时间延后。
应用服务器是weblogic
delay=0;
period=900000 //周期为15分钟
//period=1800000 //周期为30分钟
myTimer.schedule(TimerTask, delay,period);
当周期为15分钟时任务正常执行
当周期为30分钟时任务只在启动是执行一次,不能进行周期执行。
大家分析下是什么原因?