简单起见用Kotlin
写
scheduleAtFixedRate
1 2 3 4 5 6 7 8 9 10
| val timerTaskPool = Executors.newScheduledThreadPool(2) timerTaskPool.scheduleAtFixedRate( object : TimerTask() { override fun run() { println(Date()) Thread.sleep(2000) } }, 0, 3, TimeUnit.SECONDS )
|
运行结果
1 2 3
| Wed May 22 02:24:52 CST 2019 Wed May 22 02:24:55 CST 2019 Wed May 22 02:24:58 CST 2019
|
也就是不顾前面的任务有没执行完, 延迟指定时间就再次执行任务
scheduleWithFixedDelay
1 2 3 4 5 6 7 8 9 10
| val timerTaskPool = Executors.newScheduledThreadPool(2) timerTaskPool.scheduleWithFixedDelay( object : TimerTask() { override fun run() { println(Date()) Thread.sleep(2000) } }, 0, 3, TimeUnit.SECONDS )
|
运行结果
1 2 3
| Wed May 22 02:26:04 CST 2019 Wed May 22 02:26:09 CST 2019 Wed May 22 02:26:14 CST 2019
|
延迟 3 秒, 睡了 2 秒, 间隔 5 秒
定时任务尽量用 Pool, 因为 Timer 在分布式系统上可能存在时间不一致或者无法捕获异常的问题