使用计时器有一些缺点
- 它仅创建一个线程来执行任务,并且如果一个任务花费的时间太长,则其他任务会受到影响。
- 它不处理任务引发的异常,线程只是终止,这会影响其他计划的任务,并且它们永远不会运行
ScheduledThreadPoolExecutor可以正确处理所有这些问题,因此使用Timer没有意义。.在您的情况下,可以使用两种方法。.scheduleAtFixedRate(…)和scheduleWithFixedDelay(..)
class MyTask implements Runnable { @Override public void run() { System.out.println("Hello world"); } }ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);long period = 100; // the period between successive executionsexec.scheduleAtFixedRate(new MyTask(), 0, period, TimeUnit.MICROSECONDS);long delay = 100; //the delay between the termination of one execution and the commencement of the nextexec.scheduleWithFixedDelay(new MyTask(), 0, delay, TimeUnit.MICROSECONDS);


