问题描述
Timer timer = new Timer();
TimerTask tt = new TimerTask() {
public void run() {
System.out.println("Timer started");
//my Logic
};
};
timer.schedule(tt,60000,60000);
上述计时器每 1 分钟运行一次。 执行此代码没有任何问题。
因为这段代码有内部类并且它也覆盖了run方法 我想知道有没有其他有效的方法来编写定时器逻辑,或者这是我们处理定时器的唯一方法。
解决方法
tl;博士
您要求:
没有内部类的 Java Timer 功能
将您的任务定义为实现 Runnable
接口的单独类,并将实例提交给 ScheduledExecutorService
对象。
您会在不涉及内部类的情况下重复执行。
使用执行器服务
如 their Javadoc 中所述,Timer
/TimerTask
类已被添加到 Java 5 的执行程序框架所取代。请参阅 tutorial by Oracle。
从 Executors
类中获取执行程序服务对象。要安排重复任务,请获取 ScheduledExecutorService
。
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor() ;
定义单独的类实现 Runnable
提交您的任务作为 Runnable
类型的对象执行。此接口需要一个方法 run
,由执行程序服务调用。
public class TellTime implements Runnable
{
public void run()
{
System.out.println( "Now is " + Instant.now() ) ;
}
}
实例化。
Runnable task = new TellTime() ;
传递给您的执行程序服务。其他参数指定等待多长时间直到第一次运行,然后重复执行的频率。
ses.scheduleAtFixedRate( task,1,TimeUnit.MINUTES ) ;
请务必最终关闭您的执行程序服务。否则它的后备线程池可能会无限期地继续下去,就像僵尸?♂️。
,如果您使用的是 Java 8,您可以简化代码:
import java.util.Timer;
..
Timer timer = new Timer();
timer.schedule(() -> doSomething(),60000);