From 9a52a277b953a5f92a7a9c9bbce3f8a5bc2741b3 Mon Sep 17 00:00:00 2001 From: Steve Hannah Date: Wed, 17 Feb 2016 11:46:10 -0800 Subject: [PATCH] Added Timer.scheduleTaskAtFixedRate() method --- .../org/teavm/classlib/java/util/TTimer.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/classlib/src/main/java/org/teavm/classlib/java/util/TTimer.java b/classlib/src/main/java/org/teavm/classlib/java/util/TTimer.java index aeb24a736..7e5df559b 100644 --- a/classlib/src/main/java/org/teavm/classlib/java/util/TTimer.java +++ b/classlib/src/main/java/org/teavm/classlib/java/util/TTimer.java @@ -81,4 +81,33 @@ public class TTimer extends TObject { }; task.nativeTimerId = Window.setTimeout(handler, (int) delay); } + + public void scheduleAtFixedRate(final TTimerTask task, long delay, long period) { + if (cancelled || task.timer != null || task.nativeTimerId >= 0) { + throw new TIllegalStateException(); + } + final long[] nextStartTime = new long[]{System.currentTimeMillis() + delay}; + task.timer = this; + TimerHandler handler = new TimerHandler() { + @Override public void onTimer() { + new Thread(() -> { + if (cancelled || task.timer == null) { + return; + } + long nextDelay = nextStartTime[0] - System.currentTimeMillis(); + if (nextDelay < 0 ) { + nextDelay = 0; + } + task.nativeTimerId = Window.setTimeout(this, (int) nextDelay); + nextStartTime[0] += period; + TTimerTask.performOnce(task); + if (!cancelled) { + task.timer = TTimer.this; + } + }).start(); + } + }; + task.nativeTimerId = Window.setTimeout(handler, (int) delay); + nextStartTime[0] += period; + } }