关于Timer和TimerTask实验测试

今天发现一job任务一直在耗cpu,一直没有释放资源,jconsole跟踪发现任务没有真正kill掉,因为job任务里面执行了数据库操作,导致一直锁在了那里,后来通过时间条件来kill掉此任务,使cpu恢复了正常!下面做了个测试:

import java.util.Timer;
import java.util.TimerTask;

/*
 * 说明:该代码主要是说明如何在定时器外部,通过执行时间等条件来停止某些任务
 *
 */
public class Reminder {

	Timer timer;

	public Reminder(int seconds) {
		timer = new Timer(); //初始化一定时器
		RemindTask rt = new RemindTask();

		//定时器将延迟seconds秒开始执行RemindTask这个任务,然后每隔2秒执行一次RemindTask任务
		timer.schedule(rt, seconds * 1000, 2000);

		//执行的时间超过了5秒,kill掉定时器中的任务 & 定时器
		long beginTime = System.currentTimeMillis();
		long nowTime   = 0L;
		while (true) {
			nowTime = System.currentTimeMillis();
			if (nowTime - beginTime >= 20000) {
				rt.cancel();
				timer.cancel();
				break;
			}
		}
	}

	//准备给定时器触发的任务
	class RemindTask extends TimerTask {
		public void run() {
			System.out.println("Time's up!");
			//这里可以执行很多操作
		}
	}

	//test here
	public static void main(String args[]) {
		System.out.println("About to schedule task.");
		new Reminder(5);//5秒钟开始执行任务
		System.out.println("Task scheduled.");
	}
}

关于cancel的说明:
这里面有两种cancel,但是并不是cancel掉某个任务,这个任务马上就停止执行,有下列几种情况:
一、对于rt.cancel();
1、如果任务已经放入定时器里面且只会执行一次,但还没有开始执行或到执行的时间,它将再也不会执行了。
2、如果任务已经放入定时器里面且会多次执行,它将再也不会执行了。
3、如果当前cancel的任务正在执行,这个任务将继续执行完,但是在定时器里面不会再执行了,也就是让它把该干的活还是得干完再去死O(∩_∩)O~

二、对于timer.cancel();
1、这个其实是终止定时器功能,cancel时将丢弃所有该执行的任务,但是不会干扰当前正在执行的任务。

对于上面的两种cancel都是可以重复调用的,所以大家不用担心重复执行会出错O(∩_∩)O~

发表评论

电子邮件地址不会被公开。 必填项已用*标注

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>