java定期执行,如何在java中定期执行操作?

Is there any way of creating a loop that would do the task every 3 secs without using a sleep function

For eg:

try {

while (true) {

System.out.println(new Date());

Thread.sleep(5 * 1000);

}

} catch (InterruptedException e) {

e.printStackTrace();

}

But the problem while using sleep function is that, it just freezes the program.

The main idea of this loop is to get a sync with mysql database

(online).

解决方案

Use java.util.TimerTask

java.util.Timer t = new java.util.Timer();

t.schedule(new TimerTask() {

@Override

public void run() {

System.out.println("This will run every 5 seconds");

}

}, 5000, 5000);

If you are using a GUI, you can use the javax.swing.Timer, example:

int delay = 5000; //milliseconds

ActionListener taskPerformer = new ActionListener() {

public void actionPerformed(ActionEvent evt) {

System.out.println("This will run every 5 seconds");

}

};

new javax.swing.Timer(delay, taskPerformer).start();

Some info about the difference between java.util.Timer and java.swing.Timer:

http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html

Both it and javax.swing.Timer provide the same basic functionality,

but java.util.Timer is more general and has more features. The

javax.swing.Timer has two features that can make it a little easier to

use with GUIs. First, its event handling metaphor is familiar to GUI

programmers and can make dealing with the event-dispatching thread a

bit simpler. Second, its automatic thread sharing means that you don't

have to take special steps to avoid spawning too many threads.

Instead, your timer uses the same thread used to make cursors blink,

tool tips appear, and so on.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值