3.5.2.4.4. 定时器

定时器是一个非可见的界面组件,可以以一定的时间间隔运行一些界面控制器的代码。定时器是在一个处理用户事件的线程里面运行的,所以可以更新界面组件。当创建定时器的界面被关闭之后,定时器就会停止工作了。

该组件对应的 XML 名称:timer

在 Web 客户端,定时器是基于浏览器的轮询(polling)机制实现,在 desktop 客户端,是基于 javax.swing.Timer 实现的。

创建定时器的主要方法是在界面的 XML 描述中进行声明 - 使用 timers 元素,位置在 dsContextlayout 元素之间。

  • delay - 必选属性;按毫秒定义定时器执行的时间间隔。

  • autostart – 可选属性;当设置成 true 的时候,定时器会在界面打开的时候立即自动启动。默认值是 false,也就是说只有在调用定时器的 start() 方法之后才会启动。

  • repeating – 可选属性;开启定时器的重复执行模式。如果这个属性设置的是 true,定时器会按照 delay 设置的时间间隔反复一轮一轮的执行。否则只会在 delay 设定的毫秒时间之后执行一次。

  • onTimer – 可选属性;定义一个当定时器触发的时候需要执行的方法名称。这个对应的方法必须定义在界面控制器中,需要是 public 的,而且有一个 com.haulmont.cuba.gui.components.Timer 类型的参数。

下面这个例子演示了使用定时器来周期性的刷新表格内容:

<window ...
  <dsContext>
      <collectionDatasource id="bookInstanceDs" ...
  </dsContext>
  <timers>
      <timer delay="3000" autostart="true" repeating="true" onTimer="refreshData"/>
  </timers>
  <layout ...
@Inject
private CollectionDatasource bookInstanceDs;

public void refreshData(Timer timer) {
    bookInstanceDs.refresh();
}

定时器可以注入一个界面控制器,也可以通过 Window.getTimer() 方法获得。定时器的执行可以用定时器的 start()stop() 方法控制。对于已经启动的定时器,会忽略再次调用 start(),但是当定时器使用 stop() 方法停止之后,可以通过 start() 方法再次启动。

下面这个例子演示了在 XML 中定义定时器,然后在控制器里面使用定时器监听:

<timers>
    <timer id="helloTimer" delay="5000"/>
</timers>
@Inject
private Timer helloTimer;
@Inject
private Notifications notifications;

@Subscribe("helloTimer")
protected void onHelloTimerTimerAction(Timer.TimerActionEvent event) { (1)
    notifications.create()
            .withCaption("Hello")
            .show();
}

@Subscribe("helloTimer")
protected void onHelloTimerTimerStop(Timer.TimerStopEvent event) { (2)
    notifications.create()
            .withCaption("Timer is stopped")
            .show();
}

@Subscribe
protected void onInit(InitEvent event) { (3)
    helloTimer.start();
}
1 定时器执行处理器
2 定时器停止事件
3 启动定时器

定时器也可以在控制器里面创建,如果是这样的话,需要显式的把这个定时器加到界面中,比如:

@Inject
private Notifications notifications;
@Inject
private UiComponents uiComponents;

@Subscribe
protected void onInit(InitEvent event) {
    Timer helloTimer = uiComponents.create(Timer.NAME);
    getWindow().addTimer(helloTimer); (1)
    helloTimer.setId("helloTimer"); (2)
    helloTimer.setDelay(5000);
    helloTimer.setRepeating(true);

    helloTimer.addTimerActionListener(e -> { (3)
        notifications.create()
                .withCaption("Hello")
                .show();
    });

    helloTimer.addTimerStopListener(e -> { (4)
        notifications.create()
                .withCaption("Timer is stopped")
                .show();
    });

    helloTimer.start(); (5)
}
1 在页面中添加定时器
2 设置定时器参数
3 添加执行处理器
4 添加停止事件监听器
5 启动定时器