用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定时执行任务 的相关文章

  • Objective C - 音频延迟估计的互相关

    我想知道是否有人知道如何执行互相关两个音频信号之间iOS 我想将接收器 我正在从麦克风接收信号 处获得的 FFT 窗口与发射器处 正在播放音轨 处的 FFT 窗口对齐 即确保每个窗口的第一个样本 除了发射机的 同步 周期之外 也将是接收机的
  • Android中每10秒显示一次数据

    我必须每 10 秒后显示一些数据 谁能告诉我该怎么做 您还可以使用另一种方法按特定时间间隔更新 UI 以上两个选项都是正确的 但根据具体情况 您可以使用替代方法在特定时间间隔更新 UI 首先为 Handler 声明一个全局变量 用于从 Th
  • 在 JavaScript 中,如何让函数在特定时间运行?

    我有一个托管仪表板的网站 我可以编辑页面上的 JavaScript 目前每五秒刷新一次 我现在正在尝试获得window print 每天早上8点跑步 我怎么能这样做呢 JavaScript 是not用于此目的的工具 如果您希望某些东西在每天
  • 对于特定用户 MySQL,查找同一表内的日期范围重叠

    我绝不是 MySQL 专家 所以我正在寻求有关此事的任何帮助 我需要执行一个简单的测试 原则上 我有这个 简化的 表 tableid userid car From To 1 1 Fiesta 2015 01 01 2015 01 31 2
  • Android 计时器/计时器任务导致我的应用程序崩溃?

    只是在我的 mainActivity 的 onCreate 中测试一个简单的代码块 Timer timer2 new Timer TimerTask testing new TimerTask public void run Toast m
  • Android:如何在触摸事件中手动实现长按?

    简短版本 我想要一种方法来在 onTouchEvent 上启动基于时间的计数器 并测试在响应之前是否已经过了一定的时间 作为手动 LongTouch 检测 解释 我有一个自定义 imageView 可以通过两根手指滑动滑入 滑出屏幕 我想向
  • C#,System.Timers.Timer,每 15 分钟运行一次,与系统时钟同步

    如何让 System Timers Timer 每 15 分钟触发一次与系统时钟同步的事件 换句话说 我希望它恰好在 xx 00 xx 15 xx 30 xx 45 触发 其中 xx 表示任何小时 您可以让它每秒流逝一次 并检查当前时间是否
  • 如果未返回,则在一段时间后终止线程

    我有一个线程从网络或串行端口获取一些数据 如果 5 秒内没有收到数据 则线程必须终止 或返回 false 换句话说 如果线程运行时间超过 5 秒 则必须停止 我用 C 编写 但任何 NET 语言都可以 有两种方法 1 封装超时 从网络或串行
  • jQuery 动画延迟

    如何使用 jQuery 延迟动画 我需要获得一个导航来扩大宽度 然后扩大高度 然后反转以获得反向动画 Code function nav li not logo nav li ul li hover function this animat
  • 使用 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
  • 如何使用 c# 编写几个精确的计时器(精确到 10 毫秒间隔)

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

    我编写了一个计时器 可以测量任何多线程应用程序中特定代码的性能 在下面的计时器中 它还会在地图中填充花费了 x 毫秒的调用次数 我将使用这张图作为我的直方图的一部分来进行进一步的分析 例如调用花费了这么多毫秒的百分比等等 public st
  • AMQP延迟传递并防止重复消息

    我有一个会偶尔生成消息的系统 我只想每 5 分钟提交零条或一条消息 如果没有生成消息 队列消费者将不会处理任何内容 如果 5 分钟内生成一百条相同的消息 我只希望从队列中使用其中一条 我正在使用AMQP RabbitMQ 有没有办法在rab
  • Javascript 函数与 php 一样吗?

    我在网站上使用 WebIM 提供聊天支持 我希望能够在客户端启动聊天会话时设置一个计时器 如果操作员 技术人员在 x 秒内没有响应 我希望页面重定向到客户端可以留言的另一个页面 有点像 请稍等 我们尝试联系您 这样 如果所有技术人员都太忙或
  • 开玩笑 setTimeout 不暂停测试

    it has working hooks async gt setTimeout gt console log Why don t I run expect true toBe true 15000 我已经查看了这个答案 Jest 文档和几
  • 如何在单击按钮时清除反应挂钩中的间隔

    我正在用反应钩子构建一个简单的计时器 我有两个按钮启动和重置 当我单击开始按钮时 handleStart 函数工作正常 计时器启动 但我不知道如何在单击重置按钮时重置计时器 这是我的代码 const App gt const timer s
  • 为什么用java日历解析时会得到错误的月份

    Date fakeDate sdf parse 15 07 2013 11 00 AM Calendar calendar Calendar getInstance calendar setTime fakeDate int current
  • 设置基于 PHP 定时器的函数

    我有一个 php 文件test php 我想要echo or print5 秒后 即在浏览器调用 加载或打开 php 文件后不久 成功 顺便说一句 有时我可能想在特定的时间间隔后执行 初始化某些函数 如何使用 php 执行面向时间的任务 例
  • 如何使用 jQuery 设置计时器来发送 HTML 表单的 HTTP post 数据

    我有一个 HTML 表单 需要使用 HTTP POST 和输入数据将其发布到服务器 具体来说 我只需要发送表单中选中的所有复选框的参数值 如果用户10分钟内没有自己做 我就需要做 我不确定实现这一目标的最佳方法 但现在我正在尝试使用 jQu
  • 使用 System.Windows.Forms.Timer.Start()/Stop() 与 Enabled = true/false

    假设我们在 Net 应用程序中使用 System Windows Forms Timer 在计时器上使用 Start 和 Stop 方法与使用 Enabled 属性之间有什么有意义的区别吗 例如 如果我们希望在进行某些处理时暂停计时器 我们

随机推荐

  • 软件工程第五章习题

    软件工程第五章习题 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是一个虚类 需要实现它的