Java定时器Timer和TimerTask的使用

Java中java.util包下的Timer和TimerTask的使用

TimerTask负责具体的执行某一任务,Timer则负责来调度TimerTak的工作。Timer通过调用 schedule 方法来周期性的执行任务或者是定时的执行任务。

以下是 schedule 方法的重载
从当前时间开始,延时 delay 毫秒,每隔 period 毫秒执行一次TimerTask中的run方法
schedule(TimerTask task, long delay, long period)
在 time 这一时间点执行 task
schedule(TimerTask task, Date time)
延时 delay 毫秒执行 task
schedule(TimerTask task, long delay)
在 firtTime 时间点开始执行task,之后每隔 period 毫秒执行一次task
schedule(TimerTask task, Date firstTime, long period)

Timer 可以负责多个 TimerTask 的调度,每调用一次schedule方法,就会新开一个线程,并且该线程会一直的执行下去,直到调用cancel方法为止。

实例:

 final Timer timer = new Timer(false);
    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            count++;
        // 自定义的Log日志工具类
            Logger.d(LOG_TAG, "time " + count + " | " + Thread.currentThread().getId());
            if (count == 50)
                timer.cancel();
        }
    };
    TimerTask task2 = new TimerTask() {
        @Override
        public void run() {
            Logger.d(LOG_TAG, "task excuted");
        }
    };
    timer.schedule(timerTask, 1000, 1000);
    Date date = new Date(System.currentTimeMillis() + 2000);
    timer.schedule(task2, date);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值