C
Chris Seidel
Hi,
i'm using a ScheduledExecutorService to schedule a task. The problem is,
that the task gets execute about 10 - 20 percent too late, e.g. when I
schdule it with 20 s delay, it gets executed after 24 s.
Is this "normal"?
Here is the testcode:
package com.foo;
import static junit.framework.Assert.assertEquals;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
public class SchedulerTest {
private ScheduledExecutorService s;
private long executedAtMillis;
@Test
public void test1() {
s = Executors.newScheduledThreadPool(1);
final long currentTimeMillis = System.currentTimeMillis();
long delay = 20000L;
s.schedule(new Runnable() {
public void run() {
executedAtMillis = System.currentTimeMillis();
}
}, delay, TimeUnit.MILLISECONDS);
try {
Thread.sleep(delay * 2);
} catch (InterruptedException e) {
}
assertEquals(delay, executedAtMillis - currentTimeMillis);
}
}
When I use java.util.Timer everything is ok:
@Test
public void test2() {
Timer t = new Timer();
final long currentTimeMillis = System.currentTimeMillis();
long delay = 20000L;
t.schedule(new TimerTask() {
@Override
public void run() {
executedAtMillis = System.currentTimeMillis();
}
}, delay);
sleep(delay);
assertEquals(delay, executedAtMillis - currentTimeMillis);
}
Thank you.
i'm using a ScheduledExecutorService to schedule a task. The problem is,
that the task gets execute about 10 - 20 percent too late, e.g. when I
schdule it with 20 s delay, it gets executed after 24 s.
Is this "normal"?
Here is the testcode:
package com.foo;
import static junit.framework.Assert.assertEquals;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
public class SchedulerTest {
private ScheduledExecutorService s;
private long executedAtMillis;
@Test
public void test1() {
s = Executors.newScheduledThreadPool(1);
final long currentTimeMillis = System.currentTimeMillis();
long delay = 20000L;
s.schedule(new Runnable() {
public void run() {
executedAtMillis = System.currentTimeMillis();
}
}, delay, TimeUnit.MILLISECONDS);
try {
Thread.sleep(delay * 2);
} catch (InterruptedException e) {
}
assertEquals(delay, executedAtMillis - currentTimeMillis);
}
}
When I use java.util.Timer everything is ok:
@Test
public void test2() {
Timer t = new Timer();
final long currentTimeMillis = System.currentTimeMillis();
long delay = 20000L;
t.schedule(new TimerTask() {
@Override
public void run() {
executedAtMillis = System.currentTimeMillis();
}
}, delay);
sleep(delay);
assertEquals(delay, executedAtMillis - currentTimeMillis);
}
Thank you.