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);
添加回答
举报