---
title: "ScheduledExecutorService scheduleWithFixedDelay and scheduleAtFixedRate"
author: "jusi"
date: "2014-12-03T23:35:48Z"
tags: []
categories: ["编程语言"]
slug: "scheduledexecutorservice-schedulewithfixeddelay-and-scheduleatfixedrate"
draft: false
lastmod: "2014-12-03T23:37:15Z"
id: 2163050
url: "https://jusi.iteye.com/blog/2163050"
---

ScheduledExecutorService has 2 method to schedule a task

- schedule with fixed delay
- schedule at fixed rate

I was confused about delay and rate, they both require a time parameter. What's the difference?

I ran following code:

```
public static void main(String[] args) {
        ScheduledExecutorService executors = Executors.newSingleThreadScheduledExecutor();
        executors.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                System.out.println(new Date());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, 0, 5, TimeUnit.SECONDS);
    }
```

 And I got such a result on console. It will print a log every 10 seconds.

```
Wed Dec 03 23:13:44 CST 2014
Wed Dec 03 23:13:54 CST 2014
Wed Dec 03 23:14:04 CST 2014
```

 I ran same code with the other method, this time I got:

```
Wed Dec 03 23:26:48 CST 2014
Wed Dec 03 23:26:53 CST 2014
Wed Dec 03 23:26:58 CST 2014
```

 

- "schedule with fixed delay" would delay given time since last task **finished** to start next execution
- "schedule at fixed rate" would wait given time since last task **start** to start next execution, if duration exceed given time, next task will be executed immediately.