3 回答

TA貢獻1808條經驗 獲得超4個贊
您還可以查看Timer和TimerTask類,這些類可用于計劃任務每秒鐘運行一次n。
您需要一個擴展TimerTask并覆蓋該public void run()方法的類,該類將在每次將該類的實例傳遞給timer.schedule()方法時執行。
這是一個示例,Hello World每5秒打印一次:-
class SayHello extends TimerTask {
public void run() {
System.out.println("Hello World!");
}
}
// And From your main() method or any other method
Timer timer = new Timer();
timer.schedule(new SayHello(), 0, 5000);

TA貢獻1810條經驗 獲得超4個贊
如果要執行定期任務,請使用ScheduledExecutorService。特別是ScheduledExecutorService.scheduleAtFixedRate
編碼:
Runnable helloRunnable = new Runnable() {
public void run() {
System.out.println("Hello world");
}
};
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(helloRunnable, 0, 3, TimeUnit.SECONDS);
添加回答
舉報