Java Timer in GWT

2019-01-28 04:50发布

问题:

I'm trying to have a Java Timer in my EntryPoint:

Timer timer = new Timer();
timer.schedule(
   new TimerTask() {
       public void run() {
           //some code
       }
   }
   , 5000);

But when trying to compile this I got: No source code is available for type java.util.Timer; did you forget to inherit a required module?

What can I do to fix this error?

回答1:

If you're using Libgdx, you can use the libgdx Timer infrastructure to schedule work to run in the future:

Timer t = new Timer();
t.scheduleTask(new Timer.Task() { 
      public void run() { /* some code */ } 
  }), /* Note that libgdx uses float seconds, not integer milliseconds: */ 5);

This way you can schedule the timer in your platform independent code. (The GWT-specific solution will only work in the platform dependent part of your project.)



回答2:

In GWT you are restricted to use all the Util package classes.

Here is the List of Classes only you can use from util class.

You can use GWT Timer class.

Example(from docs);

 public void onClick(ClickEvent event) {
    // Create a new timer that calls Window.alert().
    Timer t = new Timer() {   //import (com.google.gwt.user.client.Timer)
      @Override
      public void run() {
        Window.alert("Nifty, eh?");
      }
    };

    // Schedule the timer to run once in 5 seconds.
    t.schedule(5000);
  }