码迷,mamicode.com
首页 > 其他好文 > 详细

Akka 设置延迟执行的Future_Patterns. after

时间:2015-01-09 21:04:52      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:

Akka 设置延迟执行的Future_Patterns. after


akka.pattern.Patterns.after makes it easy to complete a Future with a value or exception after a

timeout.

代码如下,

package com.usoft;

import akka.actor.ActorSystem;
import akka.dispatch.Futures;
import akka.dispatch.OnComplete;
import akka.pattern.Patterns;
import scala.concurrent.ExecutionContext;
import scala.concurrent.Future;
import scala.concurrent.duration.Duration;

import java.util.Arrays;
import java.util.concurrent.Callable;

/**
 * Created by liyanxin on 2015/1/9.
 */
public class PatternAfterDemo {

    public static void main(String args[]) {

        ActorSystem system = ActorSystem.create("myActorSystem");
        final ExecutionContext ec = system.dispatcher();

        final Future<String> failExc = Futures.failed(new IllegalStateException("OHNOES1"));
        Future<String> delayed = Patterns.after(Duration.create(200, "millis"),
                system.scheduler(), ec, failExc);
        Future<String> future = Futures.future(new Callable<String>() {
            public String call() throws InterruptedException {
                Thread.sleep(1000);
                return "foo";
            }
        }, ec);
        Future<String> result = Futures.firstCompletedOf(Arrays.asList(future, delayed), ec);
        result.onComplete(new OnComplete<String>() {
            @Override
            public void onComplete(Throwable failure, String success) throws Throwable {
                if (failure != null) {
                    failure.printStackTrace();
                } else {
                    System.out.println(success);
                }
            }
        }, ec);
    }
}


==================================END==================================


Akka 设置延迟执行的Future_Patterns. after

标签:

原文地址:http://my.oschina.net/xinxingegeya/blog/365614

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!