sun java 运行时间,在Java中的固定时间调用方法

这篇博客介绍了如何在Java中利用Timer和TimerTask类来安排任务在特定时间(例如6:00和13:00)执行。通过创建一个Alarm类和内部的AlarmTask类,你可以设置一个后台线程在指定时间执行任务,并在完成工作后取消定时器。
摘要由CSDN通过智能技术生成

How do I call a method at a particular time?

For example to call the method at 6:00 and 13:00.

I'm working at a desktop application for Windows.

解决方案

Have a look at the Timer and TimerTask classes. You can schedule a thread to execute at a specific time, or repeatedly.

public class Alarm {

Timer _timer;

public Alarm() {

// Create a Date corresponding to 10:30:00 AM today.

Calendar calendar = Calendar.getInstance();

calendar.set(Calendar.HOUR_OF_DAY, 10);

calendar.set(Calendar.MINUTE, 30);

calendar.set(Calendar.SECOND, 0);

Date alarmTime = calendar.getTime();

_timer = new Timer();

_timer.schedule(new AlarmTask(), alarmTime);

}

class AlarmTask extends TimerTask {

/**

* Called on a background thread by Timer

*/

public void run() {

// Do your work here; it's 10:30 AM!

// If you don't want the alarm to go off again

// tomorrow (etc), cancel the timer

timer.cancel();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值