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

  • Interval 属性更改时 System.Timer 的行为

    我有一个 System Timer 设置 每天凌晨 2 点触发一个事件 如果计时器启动的进程失败那么我想要计时器 重置为每 15 分钟运行一次 直到该过程成功完成 this is how the timer is set up this i
  • VHDL 中的进程是可重入的吗?

    一个进程是否可以连续运行两次或多次VHDL 如果在进程的顺序执行未完成的情况下发生另一个事件 在敏感信号列表上 会发生什么 有可能还是我的VHDL流程中的模型完全错误 进程运行时不会发生任何事件 当进程被事件唤醒时 它会运行到完成 结束进程
  • 快速使函数中的计时器无效

    我正在尝试创建一个带有主比赛时钟和开始 停止按钮的曲棍球比赛时钟应用程序 但我的 stopGameclock 函数遇到了问题 计时器不会失效 通过在这里搜索其他问题 我认为这与我有关 var gameclockTimer NSTimer 接
  • iOS 中屏幕关闭/设备锁定时定时器不运行

    应用程序位于后台 在与 BLE 设备断开连接时会收到回调 之后应用程序必须等待一段时间 1 分钟 然后执行一些代码 如果屏幕打开 即使在后台 应用程序也会按预期运行 但是 如果屏幕关闭 则计时器将无法工作 并且应用程序不会按预期执行 这是
  • java.util.Timer:它是否已弃用?

    我在评论中读到这个答案 https stackoverflow com questions 2212848 how to genarate random numbers 2212887 2212887以及许多其他有关日程安排的问题 抱歉 没
  • .net 计时器有多可靠?

    我正在考虑在 Windows 服务中使用 System Timers Timer 我想知道它们的可靠性和准确性如何 尤其 对于它们的运行频率有任何保证吗 当处理器或内存过载时会发生什么 在这种情况下 ElapsedEventArgs Sig
  • 如何在给定的时间间隔运行 Unix 命令?

    我想运行 Unix 命令 例如ls 通过脚本每隔 5 分钟一次 解释 我有一个 Unix 脚本 在该脚本中我有一个名为 ls 的命令 我希望该脚本中的 ls 命令每 5 分钟运行一次 Use watch The nflag 指定以秒为单位的
  • 定时器可以提早吗?

    显然 System Threading Timer 回调应该会延迟一点 然而 可以提前调用吗 例如 如果您启动秒表并安排计时器在 1000 毫秒内运行回调 那么秒表是否有可能在回调中显示 999 或者我们可以指望它必须显示 1000 或更多
  • 在 Swift 上设置计时器

    我尝试重复执行函数 pepe 我没有收到错误 但它不起作用 这是我的代码 public class MyClass var timer Timer objc func pepe gt String let hola hola return
  • JavaScript - 如何等待/SetTimeOut/睡眠/延迟

    这又是我的剪刀石头布游戏 目前 用户无法看到发生了什么 因为在提示输入 石头 布或剪刀 后 他们会立即重新提示 问题是我怎样才能使程序延迟 以便他们至少可以读取正在发生的事情 我读到 JavaScript 中不存在 sleep 我正在尝试使
  • 如何将浮点数包装到区间 [-pi, pi)

    我正在寻找一些可以有效完成的不错的 C 代码 while deltaPhase gt M PI deltaPhase M TWOPI while deltaPhase lt M PI deltaPhase M TWOPI 我有什么选择 更新
  • 从当前日期减去月份 sql

    我正在尝试从今天减去日期 获取 1 个月前直到永远的报告 到目前为止我已经尝试过 DATE SUB NOW INTERVAL 1 MONTH 这是上下文 SELECT contracts currency ROUND SUM CASE WH
  • Angular2 可观察定时器条件

    我有一个计时器 initiateTimer if this timerSub this destroyTimer let timer TimerObservable create 0 1000 this timerSub timer sub
  • Clock_nanosleep() 尚不支持 CLOCK_MONOTONIC_RAW。这该如何处理呢?

    现在clock nanosleepDebian Jessie 上的 CLOCK MONOTONIC RAW 返回 EOPNOTSUPP 如何解决该问题并补偿可能应用于计时器循环中的 CLOCK MONOTONIC 的 NTP 调整 Is c
  • Android:即使调用了cancel(),CountDownTimer的finish()也会被调用

    我这样使用倒数计时器 new CountDownTimer 15000 15 public void onTick long millisUntilFinished long seconds millisUntilFinished 1000
  • 如何测量脚本的执行时间? [复制]

    这个问题在这里已经有答案了 如何测量脚本从开始运行到结束所需的时间 start timing CODE end timing EDIT 2011 年 1 月 这是最佳的可用解决方案 其他解决方案 例如performance now 现在应该
  • WPF C# - 计时器倒计时

    如何在用 WPF C 编写的代码中实现以下内容 我有一个 ElementFlow 控件 在其中实现了 SelectionChanged 事件 该事件 根据定义 在控件的项目选择发生更改时触发特定事件 我想要它做的是 启动计时器 如果计时器达
  • 如何在 PHP 或 MySQL 中查找日期是否符合某个区间?

    假设我有一个日期时间 2011 年 6 月 16 日 7 00 我希望能够在 2011 年 8 月 5 日的 7 00 进行检查 并能够知道它恰好是自第一次日期以来 1 天的倍数 而 7 01 不算在内 因为它不是精确倍数 另一个测试集 假
  • 互动倒计时增加?

    我有一个表单 如果没有完成任何鼠标交互 我想在 5 秒后关闭它 但如果完成任何鼠标交互 我希望它关闭countdown 5 seconds每次交互都会增加 5 秒 这是我到目前为止想到的 int countdown 5 System Tim
  • JavaFX 的 Swing 计时器替代方案以及线程管理差异

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

随机推荐

  • 软件工程第五章习题

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