java中实现定时器

public class TimerTaskTest extends TimerTask{ public void run() { //自己要定时实现的功能 System.out.println(new Date()); } public static void main(String[] args){ TimerTaskTest test = new TimerTaskTest(); //Timer可以为守护进程,也可以不是 Timer timer = new Timer(); //添加任务,设置时间间隔 //0:任务执行前的时间间隔,5*1000:两次任务之间的时间间隔 timer.schedule(test,0,5*1000); } }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java ,可以使用 Timer 类或者 ScheduledExecutorService 接口来实现定时器功能。 使用 Timer实现定时器的步骤如下: 1. 导入 Timer 类所在的包:`import java.util.Timer;` 2. 创建 Timer 对象:`Timer timer = new Timer();` 3. 创建一个继承自 TimerTask 类的任务类,并重写 run() 方法,定义定时执行的任务逻辑。 4. 使用 Timer 对象的 schedule() 方法来安排任务的执行时间和频率,例如:`timer.schedule(task, delay, period);` - task:要执行的任务对象 - delay:延迟多少毫秒后开始执行任务 - period:任务执行的周期,以毫秒为单位(如果只需要执行一次,则将 period 设为 0) 下面是一个简单的示例代码: ```java import java.util.Timer; import java.util.TimerTask; public class TimerExample { public static void main(String[] args) { Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { // 定时执行的任务逻辑 System.out.println("Timer task is running..."); } }; // 延迟 1000 毫秒后开始执行任务,每隔 2000 毫秒重复执行一次 timer.schedule(task, 1000, 2000); } } ``` 使用 ScheduledExecutorService 接口实现定时器的步骤如下: 1. 导入 ScheduledExecutorService 所在的包:`import java.util.concurrent.ScheduledExecutorService;` 2. 创建 ScheduledExecutorService 对象:`ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);` 3. 创建一个实现 Runnable 接口的任务类,并实现 run() 方法,定义定时执行的任务逻辑。 4. 使用 ScheduledExecutorService 对象的 scheduleAtFixedRate() 或 scheduleWithFixedDelay() 方法来安排任务的执行时间和频率,例如:`executor.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.MILLISECONDS);` - task:要执行的任务对象 - initialDelay:第一次执行任务的延迟时间 - period:任务执行的周期 - TimeUnit.MILLISECONDS:时间单位,这里使用毫秒作为单位 下面是一个使用 ScheduledExecutorService 的示例代码: ```java import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class TimerExample { public static void main(String[] args) { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); Runnable task = new Runnable() { @Override public void run() { // 定时执行的任务逻辑 System.out.println("Timer task is running..."); } }; // 延迟 1000 毫秒后开始执行任务,每隔 2000 毫秒重复执行一次 executor.scheduleAtFixedRate(task, 1000, 2000, TimeUnit.MILLISECONDS); } } ``` 以上就是在 Java 实现定时器的两种方法。你可以根据自己的需求选择适合的方式来实现定时任务
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值