开发者

How do I make sure a Timer stays alive?

I have code that relies on a Timer staying alive and managing TimerTask. Usually TimersTasks will come and go and there will always be at least one TimerTask to keep the Timer alive, but every now and then all the TimerTasks will d开发者_StackOverflow中文版ie and the Timer will die with it.

How would I keep Timer alive? Should I have one TimerTask in it at scheduled to fire at a far away date? That's what I'm leaning towards, but I want to hear what more experienced programer's ideas would be.

*It would also be nice if I could terminate all TimerTaks except for this one 'permanent' TimerTask.

Sorry if none of this makes much sense, or if I'm thinking of Timers and TimerTasks all wrong. I'm brand new to Java and all programming.


This sounds backwards. The Timer is the thing that manages the tasks. The TimerTask is the thing that is getting managed. You create a timer, you tell it to schedule the timertask, which can be singular or continuous (e.g. you can set the task to run every hour for as long as your JVM is running). It will run until it has no more tasks.

From the docs:

After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread terminates gracefully (and becomes subject to garbage collection).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜