scheduleAtFixedRate vs scheduleWithFixedDelay

后端 未结 7 1478
时光说笑
时光说笑 2020-12-04 06:18

What\'s the main difference between scheduleAtFixedRate and scheduleWithFixedDelay methods of ScheduledExecutorService?

scheduler.s         


        
7条回答
  •  温柔的废话
    2020-12-04 06:34

    Let's write a simple program:

    import java.util.concurrent.Executors
    import java.util.concurrent.TimeUnit
    
    var time = 0L
    var start = System.currentTimeMillis()
    val executor = Executors.newScheduledThreadPool(1)
    executor.scheduleWithFixedDelay({
        if (time >= 12_000L) {
            executor.shutdown()
        } else {
            Thread.sleep(2000L)
            val now = System.currentTimeMillis()
            time += now - start
            System.out.println("Total $time delay ${now - start}\n")
            start = now
        }
    }, 0L, 1000L, TimeUnit.MILLISECONDS)
    

    And see the results:

    | scheduleWithFixedDelay |   scheduleAtFixedRate  |
    |:----------------------:|:----------------------:|
    | Total 2001 delay 2001  | Total 2003 delay 2003  |
    | Total 5002 delay 3001  | Total 4004 delay 2001  |
    | Total 8003 delay 3001  | Total 6004 delay 2000  |
    | Total 11003 delay 3000 | Total 8004 delay 2000  |
    | Total 14003 delay 3000 | Total 10005 delay 2001 |
    |          ---           | Total 12005 delay 2000 |
    

    NOTICE the execution time is bigger than waiting

    scheduleWithFixedDelay keeps delay
    scheduleAtFixedRate removes delay

提交回复
热议问题