Java java.util.Timer is a utility class that can be used to schedule a thread to be executed at certain time in future. Java Timer class can be used to schedule a task to be run one-time or to be run at regular intervals.

Java java.util.Timer是一个实用程序类,可用于安排将来某个时间执行的线程。 Java Timer类可用于安排任务一次运行或定期运行。

Java TimerTask (Java TimerTask)

java.util.TimerTask is an abstract class that implements Runnable interface and we need to extend this class to create our own TimerTask that can be scheduled using java Timer class.

java.util.TimerTask是实现Runnable接口的抽象类 ,我们需要扩展该类以创建可以使用java Timer类进行调度的自己的TimerTask

Java计时器示例 (Java Timer Example)

Java Timer class is thread safe and multiple threads can share a single Timer object without need for external synchronization. Timer class uses java.util.TaskQueue to add tasks at given regular interval and at any time there can be only one thread running the TimerTask, for example if you are creating a Timer to run every 10 seconds but single thread execution takes 20 seconds, then Timer object will keep adding tasks to the queue and as soon as one thread is finished, it will notify the queue and another thread will start executing.

Java Timer类是线程安全的,并且多个线程可以共享一个Timer对象,而无需外部同步。 Timer类使用java.util.TaskQueue以给定的固定间隔添加任务,并且在任何时候都只能有一个线程运行TimerTask,例如,如果要创建一个每10秒运行一次的Timer,但是单线程执行需要20秒,然后,Timer对象将继续向队列中添加任务,一旦一个线程完成,它将通知队列,而另一个线程将开始执行。

Java Timer class uses Object wait and notify methods to schedule the tasks.

Java Timer类使用对象等待和通知方法来计划任务。

Here is a simple program for Java Timer and TimerTask example.

这是Java Timer和TimerTask示例的简单程序。

package com.journaldev.threads;import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;public class MyTimerTask extends TimerTask {@Overridepublic void run() {System.out.println("Timer task started at:"+new Date());completeTask();System.out.println("Timer task finished at:"+new Date());}private void completeTask() {try {//assuming it takes 20 secs to complete the taskThread.sleep(20000);} catch (InterruptedException e) {e.printStackTrace();}}public static void main(String args[]){TimerTask timerTask = new MyTimerTask();//running timer task as daemon threadTimer timer = new Timer(true);timer.scheduleAtFixedRate(timerTask, 0, 10*1000);System.out.println("TimerTask started");//cancel after sometimetry {Thread.sleep(120000);} catch (InterruptedException e) {e.printStackTrace();}timer.cancel();System.out.println("TimerTask cancelled");try {Thread.sleep(30000);} catch (InterruptedException e) {e.printStackTrace();}}}

Notice that one thread execution will take 20 seconds but Java Timer object is scheduled to run the task every 10 seconds. Here is the output of the program:

请注意,一个线程执行将花费20秒,但是Java Timer对象被安排为每10秒运行一次任务。 这是程序的输出:

TimerTask started
Timer task started at:Wed Dec 26 19:16:39 PST 2012
Timer task finished at:Wed Dec 26 19:16:59 PST 2012
Timer task started at:Wed Dec 26 19:16:59 PST 2012
Timer task finished at:Wed Dec 26 19:17:19 PST 2012
Timer task started at:Wed Dec 26 19:17:19 PST 2012
Timer task finished at:Wed Dec 26 19:17:39 PST 2012
Timer task started at:Wed Dec 26 19:17:39 PST 2012
Timer task finished at:Wed Dec 26 19:17:59 PST 2012
Timer task started at:Wed Dec 26 19:17:59 PST 2012
Timer task finished at:Wed Dec 26 19:18:19 PST 2012
Timer task started at:Wed Dec 26 19:18:19 PST 2012
TimerTask cancelled
Timer task finished at:Wed Dec 26 19:18:39 PST 2012

The output confirms that if a task is already executing, Timer will wait for it to finish and once finished, it will start again the next task from the queue.

输出确认如果一个任务已经在执行,Timer将等待它完成,一旦完成,它将再次从队列中开始下一个任务。

Java Timer object can be created to run the associated tasks as a daemon thread. Timer cancel() method is used to terminate the timer and discard any scheduled tasks, however it doesn’t interfere with the currently executing task and let it finish. If the timer is run as daemon thread, whether we cancel it or not, it will terminate as soon as all the user threads are finished executing.

可以创建Java Timer对象以将其作为守护程序线程运行。 Timer cancel()方法用于终止计时器并丢弃所有计划的任务,但是它不会干扰当前正在执行的任务并使其完成。 如果计时器作为守护程序线程运行,则无论我们是否取消它,它都会在所有用户线程完成执行后立即终止。

Timer class contains several schedule() methods to schedule a task to run once at given date or after some delay. There are several scheduleAtFixedRate() methods to run a task periodically with certain interval.

计时器类包含几个schedule ()方法,用于调度任务在给定日期或延迟一段时间后运行一次。 有几种scheduleAtFixedRate ()方法可按一定间隔定期运行任务。

While scheduling tasks using Timer, you should make sure that time interval is more than normal thread execution, otherwise tasks queue size will keep growing and eventually task will be executing always. That’s all for a quick roundup on Java Timer and Java TimerTask.

使用Timer计划任务时,应确保时间间隔大于正常线程执行的时间,否则任务队列大小将不断增长,最终任务将始终执行。 这就是对Java Timer和Java TimerTask的快速总结。

翻译自: https://www.journaldev.com/1050/java-timer-timertask-example

Java Timer TimerTask示例相关推荐

  1. Java Timer、TimerTask(定时任务)

    >java.util.Timer 一种工具,线程用其安排以后在后台线程中执行的任务.可安排任务执行一次,或者定期重复执行. TimerTask实现了Runnable接口,作为定时执行的任务载体. ...

  2. JAVA程序设计计时器代码_Java中的定时器Timer使用示例代码详解

    一.类概述 Timer是一种定时器工具,用来在一个后台线程计划执行指定任务.它可以计划执行一个任务一次或反复多次. TimerTask一个抽象类,它的子类代表一个可以被Timer计划的任务. 二.代码 ...

  3. Java 线程——Timer TimerTask

    Java 实现线程的三种方式: 继承自 Thread 类 继承自 Runnable 类 Timer/TimerTask Timer是一种线程设施,用于安排以后在后台线程中执行的任务.可安排任务执行一次 ...

  4. java的timertask_Java 定时器(Timer,TimerTask)详解及实例代码

    Java 定时器 在JAVA中实现定时器功能要用的二个类是Timer,TimerTask Timer类是用来执行任务的类,它接受一个TimerTask做参数 Timer有两种执行任务的模式,最常用的是 ...

  5. Timer+TimerTask实现数字时钟

    成果展示 布局 布局主题背景颜色采用#000000(纯黑色),各TextView字体颜色采用#FFFFFF(纯白色). 使用五个TextView,分别实现小时:分钟,秒钟,am,pm,周日,具体日期几 ...

  6. java web程序示例_想要建立一些有趣的东西吗? 这是示例Web应用程序创意的列表。...

    java web程序示例 Interested in learning JavaScript? Get my ebook at jshandbook.com 有兴趣学习JavaScript吗? 在js ...

  7. java timer cron_Java之旅--定时任务(Timer、Quartz、Spring、LinuxCron)

    在Java中,实现定时任务有多种方式.本文介绍4种.Timer和TimerTask.Spring.QuartZ.Linux Cron. 以上4种实现定时任务的方式.Timer是最简单的.不须要不论什么 ...

  8. Java Timer 定时器的使用

    一.延时执行首先,我们定义一个类,给它取个名字叫TimeTask,我们的定时任务,就在这个类的main函数里执行. 代码如下: package test; import java.util.Timer ...

  9. java Timer定时器管理类

    1.java timer类,定时器类.启动执行定时任务方法是timer.schedule(new RemindTask(), seconds*1000);俩参数分别是TimerTask子类,具体执行定 ...

最新文章

  1. 关于《指针的艺术》看书时所遇到的问题
  2. Leetcode 204. 计数质数 解题思路及C++实现
  3. java.lang.Thread 和 java.lang.Runnable的区别
  4. Android:Activity(页面)的生存周期
  5. npm的插件如何直接在html中使用,webpack插件之htmlWebpackPlugin
  6. jetty eclipse_3个步骤实现Jetty和Eclipse集成
  7. 【转】C/S,B/S区别
  8. 2021年快手大健康行业数据价值报告
  9. python字典的常用方法_python操作字典类型的常用方法(推荐)
  10. 从中煤陕西公司看政企移动信息化应用
  11. python数据库模糊查询_python中的mysql数据库like模糊查询
  12. CodeBlocks下载安装与SDL下载使用配置教程
  13. 网贷、助贷、信贷、借贷,你搞懂了吗?
  14. Gauss 求积公式及代码
  15. creat是什么意思中文翻译_CREAT是什么意思中文翻译
  16. 网贷魔爪再次伸向大学生,欠款账号真的能注销吗?
  17. Outlook邮件服务器eas,配置Outlook使用Outlook.com和Hotmail的两步验证
  18. 贫富差距,不是收入分化,而是资产分化
  19. 微信小程序编写一个试卷demo
  20. Promise.all、Promise.race、Promise.allSettled、Promise.any区别

热门文章

  1. 深入剖析java迭代器以及C#迭代器!
  2. HTML5与触摸界面
  3. mysql时区问题解决方案
  4. 基于 Apache Mahout 构建社会化推荐引擎
  5. tortoisegit 代码的回滚方式 --两种
  6. 第三十一篇 玩转数据结构——并查集(Union Find)
  7. subprocess,类
  8. JavaScript:判断当前浏览器是否为微信浏览器
  9. 仿分词统计的MapReduce 程序。
  10. MVVM模式下 触发器多条件判断