用java.util.Timer定时执行任务

2023-11-17

      如果要在程序中定时执行任务,可以使用java.util.Timer这个类实现。使用Timer类需要一个继承了java.util.TimerTask的类。TimerTask是一个虚类,需要实现它的run方法,实际上是他implements了Runnable接口,而把run方法留给子类实现。
      下面是我的一个例子:

class Worker extends TimerTask {
 
public void run() {
    System.
out.println("我在工作啦!");
  }

}


      Timer类用schedule方法或者scheduleAtFixedRate方法启动定时执行,schedule重载了四个版本,scheduleAtFixedRate重载了两个。每个方法的实现都不同,下面是每个方法的说明:

schedule

public void schedule(TimerTask task,
                     long delay)
Schedules the specified task for execution after the specified delay.

Parameters:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
Throws:
IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is negative.
IllegalStateException - if task was already scheduled or cancelled, or timer was cancelled.

说明:该方法会在设定的延时后执行一次任务。


schedule

public void schedule(TimerTask task,
                     Date time)
Schedules the specified task for execution at the specified time. If the time is in the past, the task is scheduled for immediate execution.

Parameters:
task - task to be scheduled.
time - time at which task is to be executed.
Throws:
IllegalArgumentException - if time.getTime() is negative.
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.

说明:该方法会在指定的时间点执行一次任务。


schedule

public void schedule(TimerTask task,
                     long delay,
                     long period)
Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.

In fixed-delay execution, each execution is scheduled relative to the actual execution time of the previous execution. If an execution is delayed for any reason (such as garbage collection or other background activity), subsequent executions will be delayed as well. In the long run, the frequency of execution will generally be slightly lower than the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

Fixed-delay execution is appropriate for recurring activities that require "smoothness." In other words, it is appropriate for activities where it is more important to keep the frequency accurate in the short run than in the long run. This includes most animation tasks, such as blinking a cursor at regular intervals. It also includes tasks wherein regular activity is performed in response to human input, such as automatically repeating a character as long as a key is held down.

Parameters:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is negative.
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.

说明:该方法会在指定的延时后执行任务,并且在设定的周期定时执行任务。


schedule

public void schedule(TimerTask task,
                     Date firstTime,
                     long period)
Schedules the specified task for repeated fixed-delay execution, beginning at the specified time. Subsequent executions take place at approximately regular intervals, separated by the specified period.

In fixed-delay execution, each execution is scheduled relative to the actual execution time of the previous execution. If an execution is delayed for any reason (such as garbage collection or other background activity), subsequent executions will be delayed as well. In the long run, the frequency of execution will generally be slightly lower than the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

Fixed-delay execution is appropriate for recurring activities that require "smoothness." In other words, it is appropriate for activities where it is more important to keep the frequency accurate in the short run than in the long run. This includes most animation tasks, such as blinking a cursor at regular intervals. It also includes tasks wherein regular activity is performed in response to human input, such as automatically repeating a character as long as a key is held down.

Parameters:
task - task to be scheduled.
firstTime - First time at which task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if time.getTime() is negative.
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.

说明:该方法会在指定的时间点执行任务,然后从该时间点开始,在设定的周期定时执行任务。特别的,如果设定的时间点在当前时间之前,任务会被马上执行,然后开始按照设定的周期定时执行任务。


scheduleAtFixedRate

public void scheduleAtFixedRate(TimerTask task,
                                long delay,
                                long period)
Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period.

In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. It is also appropriate for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another.

Parameters:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is negative.
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.

说明:该方法和schedule的相同参数的版本类似,不同的是,如果该任务因为某些原因(例如垃圾收集)而延迟执行,那么接下来的任务会尽可能的快速执行,以赶上特定的时间点。


scheduleAtFixedRate

public void scheduleAtFixedRate(TimerTask task,
                                Date firstTime,
                                long period)
Schedules the specified task for repeated fixed-rate execution, beginning at the specified time. Subsequent executions take place at approximately regular intervals, separated by the specified period.

In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. It is also appropriate for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another.

Parameters:
task - task to be scheduled.
firstTime - First time at which task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if time.getTime() is negative.
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.

说明:和上一个方法类似。

      下面是我的一个测试片断:

  public static void main(String[] args) throws Exception {
    Timer timer
= new Timer(false);
    timer.schedule(
new Worker(), new Date(System.currentTimeMillis() + 1000));
  }

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

用java.util.Timer定时执行任务 的相关文章

  • 一段时间后 NSTimer 停止在后台触发

    嘿 我正在开发一个应用程序 其中我必须每 30 秒调用一次 API 所以我为它创建了 NSTimer 但是当我的应用程序进入后台时 计时器会在 3 4 分钟后停止触发 所以它只能在后台运行 3 4 分钟 但之后就不再运行了 我如何修改我的代
  • JavaFX 的 Swing 计时器替代方案以及线程管理差异

    使用 JavaFX 的 Swing 计时器是否安全 或者 Swing 有特殊的替代方案吗 JavaFX 和 Swing 的线程管理有什么区别 事实上我很想知道相当于摇摆计时器 SwingUtilities invokeLater and i
  • Python:从区间到值的映射

    我正在重构一个函数 给定一系列隐式定义间隔的端点 检查间隔中是否包含数字 然后返回相应的值 不以任何可计算的方式相关 现在处理这项工作的代码是 if p lt 100 return 0 elif p gt 100 and p lt 300
  • Timer 和 TimerTask - 如何从 TimerTask 运行中重新安排 Timer

    基本上我想做的是制作一个在 x 秒后运行特定 TimerTask 的计时器 但随后 TimerTask 可以重新安排计时器在 y 秒后执行任务 示例如下 它在我尝试在 TimerTask 运行中安排此任务的行上给出错误 线程 Timer 0
  • 如何在实时 Windows 内核中延迟鼠标移动?

    您可以实时操纵 x 和 y 值 但如何延迟这些值以使光标看起来像缓慢移动到下一个位置 这可能吗 我尝试过在 Windows 内核驱动程序中使用等待计时器 但我不认为这是如何完成的 我不知道 最简单的延迟形式之一是定期采样 轮询 并将它们插入
  • 计时器、事件和垃圾收集:我错过了什么吗?

    考虑以下代码 class TestTimerGC Form public TestTimerGC Button btnGC new Button btnGC Text GC btnGC Click sender e gt GC Collec
  • 如何实现urllib2.urlopen的超时控制

    如何在Python中实现对urllib2 urlopen的控制 我只是想监控如果5秒内没有xml数据返回 则切断此连接并重新连接 我应该使用一些计时器吗 谢谢 urllib2 urlopen http www example com tim
  • 如何在Windows上用C语言实现定时器

    如何在 C 中创建一个计时器 时间到期后 我应该能够调用回调函数 平台是windows 有人可以指导我吗 问候 米敦 看一眼SetTimer http msdn microsoft com en us library ms644906 28
  • HashedWheelTimer 与 ScheduledThreadPoolExecutor 相比以获得更高的性能

    我正在考虑如果您需要在一台机器上的 jvm 内尽可能快地调度大量 非阻塞 任务 则应使用哪种计时器实现 我学过ScheduledThreadPoolExecutor and HashedWheelTimer来源 轮计时器一般文档 和以下是基
  • 使用 pandas.date_range() 生成多个日期时间,每周两个日期

    我在用着pd date range start date end date freq W MON 每周一生成每周频率日期时间start date 2017 01 01 and end date 2017 12 31 这意味着每月大约生成 4
  • Linux中的定时器类

    我需要一个计时器来以相对较低的分辨率执行回调 在 Linux 中实现此类 C 计时器类的最佳方法是什么 有我可以使用的库吗 如果您在框架 Glib Qt Wx 内编写 那么您已经拥有一个具有定时回调功能的事件循环 我认为情况并非如此 如果您
  • 使用 OData 模型在间隔时间内更改表的单元格

    我有这段代码 我需要我的表格显示前 10 位患者 并在 10 秒后显示接下来的 10 位患者 而无需触摸任何按钮 自动 我正在寻找与此类似的东西 https embed plnkr co ioh85m5OtPmcvPHyl3Bg https
  • 如何使用 c# 编写几个精确的计时器(精确到 10 毫秒间隔)

    我已经开始使用 C VS2010 Net Fw 4 0 进行桌面应用程序开发 涉及多个计时器 起初 我使用的是系统定时器为了通过 USB 将数据发送到数据总线 我的观点是 我需要以几个特定的 时间间隔发送不同的周期性二进制消息 例如 10m
  • 计算级别内的值

    我在 R 中生成了一组级别cut 例如假设 0 到 1 之间的小数值 分为 0 1 个区间 gt frac lt cut c 0 1 breaks 10 gt levels frac 1 0 001 0 1 0 1 0 2 0 2 0 3
  • .net 应用程序中的内存泄漏

    我正在 VB net 2005 中开发一个桌面应用程序 该应用程序包含一个间隔为 1 分钟的计时器 每次计时器计时 就会执行一组函数 大部分与数据库相关 最初 应用程序运行良好 在进程 任务管理器 中 每次调用计时器时 CPU 使用率都会达
  • 有没有比 setTimeout 更准确的方法来创建 Javascript 计时器?

    一直困扰我的是事情的不可预测性setTimeout Javascript 中的方法是 根据我的经验 计时器在很多情况下都非常不准确 我所说的不准确是指实际延迟时间似乎或多或少有 250 500 毫秒的差异 尽管这并不是一个很长的时间 但当使
  • 限制纬度和经度值的模数

    我有代表纬度和经度的双精度数 我可以轻松地将经度限制为 180 0 180 0 具有以下功能 double limitLon double lon return fmod lon 180 0 360 0 180 0 这是有效的 因为一端是排
  • 设置基于 PHP 定时器的函数

    我有一个 php 文件test php 我想要echo or print5 秒后 即在浏览器调用 加载或打开 php 文件后不久 成功 顺便说一句 有时我可能想在特定的时间间隔后执行 初始化某些函数 如何使用 php 执行面向时间的任务 例
  • 制作一个“任意键”可中断的 Python 定时器

    我正在尝试制作一个简单的计时器 它会一直计时 直到被键盘输入中断 现在我正在使用 CTRL C 来停止计时器 但我想做一些更简单的事情 例如按空格或 Enter 或 任意键 我听说这可以通过线程模块来完成 但经过几次尝试后 我显然不知道我在
  • 全局变量上的 Linux 定时器

    我在互联网上找到了下面的代码 我试图了解Linux计时器是如何工作的 无论如何 正如你在下面看到的counter1是全局变量 如果while正在处理它并且计时器关闭并改变 会发生什么counter1的值 我需要在那里加锁吗 timertst

随机推荐

  • 软件工程第五章习题

    软件工程第五章习题 1 为每种类型的模块耦合举一个具体例子 2 为每种类型的模块内聚举一个具体例子 1 为每种类型的模块耦合举一个具体例子 只需要答出什么模块和例子即可 一共5个 数控特环内 数据耦合 两个模块之间通过参数交换信息 信息仅为
  • 自动化运维管理工具 Ansible

    自动化运维管理工具 Ansible 一 Ansible介绍 Ansible是一个基于 Python开发 的配置管理和应用部署工具 现在也在自动化管理领域大放异彩 它融合了众多老牌运维工具的优点 Pubbet和Saltstack能实现的功能
  • Altium Designer侧边栏分上下或者左右两栏,并恢复

    如何分上下或左右 拖动的时候 鼠标移动到上面红框内 即可有提示 松开即完成 如何恢复 按住Shift 并鼠标拖动
  • Pytorch显存动态分配规律探索

    下面通过实验来探索Pytorch分配显存的方式 实验 显存到主存 我使用VSCode的jupyter来进行实验 首先只导入pytorch 代码如下 import torch 打开任务管理器查看主存与显存情况 情况分别如下 在显存中创建1GB
  • unity读取excel数据并绘制曲线

    一 读取数据 1 导入EPPlus类库 EPPlus dll 2 创建script脚本 3 创建空物体 挂载脚本 using System Collections using System Collections Generic using
  • android studio怎么更换默认主题?

    Android Studio默认主题IntelliJ 我们可以修改成黑色的Dracula的主题或者是Windows主题 1 首先双击桌面Android Studio图标 打开Android Studio 2 选择Android Studio
  • python3 nelink

    https github com facebookarchive gnlpy blob master netlink py 其中 注意这的encode decode 操作 class NulStringType object Ensure
  • hive-03-hive的分区

    1 hive分区与Bucket的畏难情绪 刚刚开始学习 这个的时候 一直感觉他比较难 看名字就觉得不好理解 但是实际上学起来超级简单 出现背景 这个东西为什么出来呢 来看一个需求 技术的的出现总是因为有了需求才会诞生的 假设我们有数据宾馆的
  • 1x pcie 引脚_PCIe 接口 引脚定义 一览表

    针脚号 定义 B 说明 定义 A 说明 1 12V 12V电压 PRSNT1 热拔插存在检测 2 12V 12V电压 12V 12V电压 3 RSVD 保留针脚 12V 12V电压 4 GND 地 GND 地 5 SMCLK 系统管理总线时
  • mac 安装 Adobe CC XD

    Adobe CC XD 在中国区已经免费 没什么破解一说 1 打开网址 https www adobe com cn products xd html 点击免费获取XD 下载 XD Installer dmg 2 双击 XD Install
  • sqli-labs/Less-13

    首先需要判断一下注入类型 输入如下 admin 存在报错信息 所以可以进行报错注入 但是无论正确与否都不会存在回显所以不能使用联合注入这题我们就是用报错注入吧 然后从报错信息我们可以知道注入类型为单引号注入 而且带有一个括号 我们进行作证
  • 图扑智慧城市

    十四五 新型城镇化实施方案 提出围绕提升城市治理能力智慧化水平提高数字政府服务能力 推行城市数据一网通用 城市运行一网统管 政务服务一网通办 公共服务一网通享 增强城市运行管理 决策辅助和应急处置能力 构建 人 企 地 物 政 五张城市基础
  • 输入商品单价和商品数量(输入负数时代表输入结束),自动计算商品总价,若支付金额不足会提示生育应付金额

    输入商品单价和商品数量 输入负数时代表输入结束 自动计算商品总价 若支付金额不足会提示生育应付金额 package day04 import java util Scanner public class Demo04 public stat
  • 在b站上跟着沐神学习深度学习

    算是给自己做个记录吧 每次学习之后都做点自己的笔记 加深一下印象吧 之前也看过一些资料 但是到头来还是有点乱 立下此贴为证 好好学习
  • python三位数水仙花数(附零基础学习资料)

    前言 所以直接上代码 python输入一个水仙花数 三位数 输出百位十位个位 从控制台输入一个三位数num 如果是水仙花数就打印num是水仙花数 否则打印num不是水仙花数 任务 1 定义变量num用于存放用户输入的数值 2 定义变量gw
  • TS中的泛型

    一 泛型是什么 有什么作用 当我们定义一个变量不确定类型的时候有两种解决方式 使用any 使用any定义时存在的问题 虽然 以 知道传入值的类型但是无法获取函数返回值的类型 另外也失去了ts类型保护的优势 使用泛型 泛型指的是在定义函数 接
  • 解除Discuz!X2的15分钟锁定

    第一种方法 清两个failedlogin空表 解除用户锁定 mysql gt delete from pre common failedlogin Query OK 1 row affected 0 02 sec 解除UC用户锁定 mysq
  • C/C++学习记录--double和float的区别

    单精度浮点数 float 与双精度浮点数 double 的区别如下 1 在内存中占有的字节数不同 单精度浮点数在机内占4个字节 双精度浮点数在机内占8个字节 2 有效数字位数不同 单精度浮点数有效数字8位 双精度浮点数有效数字16位 3 所
  • HertzBeat监控部署及使用

    易用友好的高性能监控告警系统 网站监测 PING连通性 端口可用性 数据库监控 API监控 自定义监控 阈值告警 告警通知 邮件微信钉钉飞书 安装部署 HertzBeat最少依赖于 关系型数据库MYSQL8 实际亲测用mysql5 7 也行
  • 用java.util.Timer定时执行任务

    用java util Timer定时执行任务 如果要在程序中定时执行任务 可以使用java util Timer这个类实现 使用Timer类需要一个继承了java util TimerTask的类 TimerTask是一个虚类 需要实现它的