codecamp

执行定期和延迟的操作

在Vert.x 中执行定期和延迟的操作是非常常见的。

在标准 verticles 中,不能使用thread sleep 引入延迟,这样会止事件循环线程。

相反,您可以使用 Vert.x 计时器。定时器可以一次性的计时器或定期的计时器。我们将讨论两个

一次性的计时器

一个单次定时器有一定的延迟之后调用一个事件处理程序,以毫秒为单位表示。

使用setTimeout方法启动计时器,

long timerID = vertx.setTimer(1000, id -> {
  System.out.println("And one second later this is printed");
});

System.out.println("First this is printed");

返回值是一个唯一的定时器 id,以后可用于取消计时器。该处理器还通过定时器id。

定期计时器

您还可以设置一个计时器来定期启动,通过使用setPeriodic方法。

会有一个初始延迟等于周期。

setPeriodic的返回值是一个唯一的计时器的 id (long)。如果以后计时器需要取消,可以使用id。

传递到计时器事件处理程序的参数也是唯一的计时器的 id:

请记住,计时器会定期触发。如果你的周期性处理需要相当长的时间进行,你的计时器事件可以运行连续或更糟的是: 堆积。

在这种情况下,您应该考虑使用setTimer替代。一旦您处理已完成,您可以设置下一个计时器。

long timerID = vertx.setPeriodic(1000, id -> {
  System.out.println("And every second this is printed");
});

System.out.println("First this is printed");

取消计时器

若要取消一个定期的计时器,请调用cancelTimer指定的计时器的 id。例如:

vertx.cancelTimer(timerID);


Context对象
Verticles 自动清理
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

编写 TCP 服务器和客户端

编写 HTTP 服务器和客户端

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }