定时器 Timer

定时器 Timer

在jdk的库中,Timer工具类的主要作用是设置计划任务的,旨在指定的时间开始执行某一个任务。

TimerTask类为抽象类,主要作用是封装任务的。

Timer对应的方法:

schedule(TimerTask task, Date time) 

该方法的作用为在指定的日期执行一次某个任务。若是执行任务时间晚于当前时间,表明该任务在将来执行。若是执行任务时间早于当前时间,表明该任务会立即执行。

schedule(TimerTask task, Date firstTime, long period)

该方法的作用为在指定的日期之后按指定的时间间隔无限循环执行某个任务。若是执行任务时间晚于当前时间,表明该任务在将来执行。若是执行任务时间早于当前时间,表明该任务会立即执行。

cancel()

该方法的作用为终止该计时器。Timer类中的该方法会将任务队列中的全部任务清空。

TimerTask

cancel()

该方法的作用为终止该计时器。TimerTask类中的该方法只清除自身任务。

例子:

public class MyTask extends TimerTask {

	@Override
	public void run() {
		System.out.println("1122222222");
	}
}

public class Test1 {

	private static Log log = LogFactory.getLog(Test1.class);

	public static void main(String[] args) {
		long newTime = System.currentTimeMillis();
		log.info("newTime:" + newTime);

		long scheduleTime = (newTime - 5000);
		log.info("scheduleTime:" + scheduleTime);
		MyTask myTask = new MyTask();
		Timer timer = new Timer();
		timer.schedule(myTask, new Date(scheduleTime));
	}
}

结果:
2021-06-16 20:26:36,019 [timer.Test1.main(Test1.java:15)]-[INFO] newTime:1623846396018
2021-06-16 20:26:36,025 [timer.Test1.main(Test1.java:19)]-[INFO] scheduleTime:1623846391018
1122222222

在输出完结果后,可以看到下图中任务虽然结束,但是进程还没有销毁。

现象:

原因:

在new Timer()时启动了一个新的非守护线程

// 在创建Timer时,调用完无参构造函数后调用一参构造函数,在一参构造函数里会开启一个新的线程。
Timer timer = new Timer();

/**
 * Creates a new timer.  The associated thread does <i>not</i>
 * {@linkplain Thread#setDaemon run as a daemon}.
 */
public Timer() {
    this("Timer-" + serialNumber());
}

/**
 * Creates a new timer whose associated thread has the specified name.
 * The associated thread does <i>not</i>
 * {@linkplain Thread#setDaemon run as a daemon}.
 *
 * @param name the name of the associated thread
 * @throws NullPointerException if {@code name} is null
 * @since 1.5
 */
public Timer(String name) {
        thread.setName(name);
        thread.start();
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值