2019独角兽企业重金招聘Python工程师标准>>>
akka提供了两个关于时长的数据类型:Duration 和 Deadline,比如5秒钟这种含义。
Duration.Inf表示无限,Duration.MinusInf表示负无限
Deadline, 表示一个绝对的时间点,意义是最终期限,并且支持通过计算当前时间到deadline之间的差距来生成Duration
下面是使用方法:
import akka.util.Duration
import java.util.concurrent.TimeUnit
import akka.util.FiniteDuration
import akka.util.Deadline
import akka.dispatch.Await
import akka.dispatch.Futures
import java.util.concurrent.Callable
import akka.dispatch.Future
import akka.actor.ActorSystem
class DurationTest extends GroovyTestCase {
def testDurationUse() {
println new FiniteDuration(5, TimeUnit.SECONDS)
println Duration.create(5d, TimeUnit.SECONDS)
println Duration.create(5, "second")
println Duration.create(5L, "second")
println()
println Duration.parse("5second")
println Duration.parse("5 second")
println Duration.parse("5 seconds")
println Duration.parse("5seconds")
println()
println Duration.Inf()
println Duration.Zero()
println Duration.MinusInf()
}
def testDeadline() {
Deadline d = Duration.create(5, "second").fromNow()
def future = Futures.future(new Callable<String>() {
String call() {
println "start...";
sleep(1000 * 60);
println("end...");
return "sd";
}
}, ActorSystem.create("test").dispatcher())
String result = (String) Await.result(Futures.future({println "start..."; sleep(1000 * 60); println("end..."); return "sd";} as Callable, ActorSystem.create("test").dispatcher()), d.timeLeft())
sleep(1000 * 60)
}
def testDeadline2() {
Future<String> f = Futures.future(new Callable<String>() {
public String call() {
return "Hello" + "World";
}
}, ActorSystem.create("test").dispatcher());
String result = (String) Await.result(f, Duration.create(5, "second"));
println result
}
}