问题
I need a clarification about the Codename One UITimer
.
For example, if I want to execute the same code every two seconds, a code like UITimer.timer(2000, true, () -> { do something; });
works until the user stays in the current Form
? Is that right?
If I want to execute the same code every two seconds regardless the shown Form
, have I to use something different from UITimer
, like a custom separate thread? For example the following code?
Form hi = new Form("Hi World", BoxLayout.y());
hi.add(new Label("Hi World"));
hi.show();
EasyThread.start("MyTimer").run(() -> {
boolean executeMe = true;
while (executeMe) {
Log.p("Do something every two seconds...");
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Log.p("Stopping the EasyThread \"MyTimer\" because an exception");
Log.e(ex);
executeMe = false;
}
}
});
Moreover, if I execute this example code, the first logged line is:
[MyTimer] 0:0:0,59 - Codename One revisions: 8b451ecb7bfbe60baf91006441e7d7d9c46afe09
Why is that line logged by my custom thread instead of by the EDT?
回答1:
Yes, UITimer
is an animation associated with the current Form
. It doesn't draw anything but uses the builtin animation mechanism which runs on the EDT. Notice that if you leave a form and return to it the timer will continue e.g.:
- Opened form at 0 time and set a timer for 15 seconds
- Went to different form at 7 seconds
- Returned to original after 30 seconds - the timer will fire immediately on return
You can also use a regular Timer
or Thread
. However, for your specific code EasyThread
doesn't provide a benefit over a regular thread since it runs in an infinite loop. The benefit of EasyThread
is in it's job processing ability.
Notice that you would need to use callSerially
to return to the EDT when working with such timers/threads.
来源:https://stackoverflow.com/questions/53994773/clarification-on-how-codename-one-uitimer-works