Future 是异步计算的结果表示,与 NodeJS 中的 Promise 类似。继承了两种能力:异步任务和流水线处理。




有返回的异步任务
@Test
public void supplyAsync() throws ExecutionException, InterruptedException {
CompletableFuture<String> boil = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(2);
return "烧水";
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
String s = boil.get();
Assert.assertEquals("烧水", s);
}
没有返回的异步任务
@Test
public void runAsync() {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
CompletableFuture<Void> run = CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
run.join();
stopWatch.stop();
double totalTimeSeconds = stopWatch.getTotalTimeSeconds();
Assert.assertEquals(1, totalTimeSeconds, 0.1);
}
/**
* 正在洗菜
*切菜:猪肉
*/
@Test
public void thenAccept() {
CompletableFuture<String> audience = CompletableFuture.supplyAsync(() -> {
System.out.println("正在洗菜");
return "猪肉";
});
CompletableFuture<Void> end = audience.thenAccept(it -> {
System.out.println("切菜:" + it);
});
end.join();
}
/**
*正在烧水...
*正在包饺子
*水开了
*饺子包好了
*准备,下10个饺子
*/
@Test
public void thenAcceptBoth() {
CompletableFuture<Void> water = CompletableFuture.runAsync(() -> {
try {
System.out.println("正在烧水...");
TimeUnit.SECONDS.sleep(4);
System.out.println("水开了");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
CompletableFuture<String> dumpling = CompletableFuture.supplyAsync(() -> {
try {
System.out.println("正在包饺子");
TimeUnit.SECONDS.sleep(5);
System.out.println("饺子包好了");
return "10个饺子";
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
});
CompletableFuture<Void> end = water.thenAcceptBoth(dumpling, (a, b) -> {
System.out.println("准备,下" + b);
});
end.join();
}
/**
*正在烧水...
*充钱
*余额不足
*/
@Test
public void exception() {
CompletableFuture<Void> water = CompletableFuture.runAsync(() -> {
System.out.println("正在烧水...");
TimeUnit.SECONDS.sleep(4);
throw new IllegalArgumentException("没燃气了");
});
CompletableFuture<Void> end = water.exceptionally(throwable -> {
System.out.println("充钱");
throw new RuntimeException("余额不足");
});
try {
end.join();
} catch (CompletionException e) {
System.out.println(e.getCause().getMessage());
Assert.assertEquals("余额不足", e.getCause().getMessage());
}
}
/*
* 1. handle..() 不会抓获异常 ,所以配置多个都会被执行;
* 2. exceptionally() 会抓获异常所以只生效一次。
* 3. exceptionally() 必须在结束前调用,否则不生效
*我是handleAsync
*我是handleAsync2
*我是handle
*我是exceptionally1
*/
@Test
public void multiExceptionHandle() {
CompletableFuture<Object> handle = CompletableFuture.runAsync(() -> {
throw new RuntimeException("异常");
})
.handleAsync((aVoid, throwable) -> {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("我是handleAsync");
return null;
})
.handle((o, throwable) -> {
System.out.println("我是handle");
return null;
})
.handleAsync((avoid, throwable) -> {
System.out.println("我是handleAsync2");
throw new RuntimeException("处理异常中的异常");
// return null;
})
.exceptionally(throwable -> {
System.out.println("我是exceptionally1");
return null;
})
.exceptionally(throwable -> {
System.out.println("我是exceptionally2");
return null;
})
;
handle.join();
}
/**
* 如果将主动抛异常的时机延长到6s,
* 由于该节点计算5s就完成, 所以不会收到异常
*
* 否则收到异常:手动失败
*/
@Test
public void obtException() throws InterruptedException, ExecutionException, TimeoutException {
CompletableFuture<String> fu = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(5);
System.out.println("成功执行了");
} catch (InterruptedException ignored) {
}
return null;
});
CompletableFuture<String> end = fu.exceptionally(throwable -> {
System.out.println("收到异常:" + throwable.getMessage());
return null;
});
TimeUnit.SECONDS.sleep(3);
// 如果等6s后再抛,由于结果已经计算完成,则不会受到异常
// TimeUnit.SECONDS.sleep(6);
fu.obtrudeException(new RuntimeException("手动失败"));
end.join();
}
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby中使用两个参数异步运行exe吗?我已经尝试过ruby命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何rubygems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除
如何使用RSpec::Core::RakeTask初始化RSpecRake任务?require'rspec/core/rake_task'RSpec::Core::RakeTask.newdo|t|#whatdoIputinhere?endInitialize函数记录在http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/RakeTask#initialize-instance_method没有很好的记录;它只是说:-(RakeTask)initialize(*args,&task_block)AnewinstanceofRake
我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我
我写了一个非常简单的rake任务来尝试找到这个问题的根源。namespace:foodotaskbar::environmentdoputs'RUNNING'endend当在控制台中执行rakefoo:bar时,输出为:RUNNINGRUNNING当我执行任何rake任务时会发生这种情况。有没有人遇到过这样的事情?编辑上面的rake任务就是写在那个.rake文件中的所有内容。这是当前正在使用的Rakefile。requireFile.expand_path('../config/application',__FILE__)OurApp::Application.load_tasks这里
在我做的一些网络开发中,我有多个操作开始,比如对外部API的GET请求,我希望它们同时开始,因为一个不依赖另一个的结果。我希望事情能够在后台运行。我找到了concurrent-rubylibrary这似乎运作良好。通过将其混合到您创建的类中,该类的方法具有在后台线程上运行的异步版本。这导致我编写如下代码,其中FirstAsyncWorker和SecondAsyncWorker是我编写的类,我在其中混合了Concurrent::Async模块,并编写了一个名为“work”的方法来发送HTTP请求:defindexop1_result=FirstAsyncWorker.new.async.
我以前没有使用过cron,所以我不能确定我这样做是对的。我想要自动化的任务似乎没有运行。我在终端中执行了这些步骤:sudogeminstall每当切换到应用程序目录无论何时。(这创建了文件schedule.rb)我将此代码添加到schedule.rb:every10.minutesdorunner"User.vote",environment=>"development"endevery:hourdorunner"Digest.rss",:environment=>"development"end我将此代码添加到deploy.rb:after"deploy:symlink","depl
如何在Rake任务中运行Capybara功能?例如:访问('http://google.com')谢谢! 最佳答案 在任务中尝试这样的事情:require'capybara'require'capybara/dsl'Capybara.current_driver=:seleniumBrowser=Class.new{includeCapybara::DSL}page=Browser.new.pagepage.visit("http://www.google.com")puts(page.html)
我正在根据Rakefile中的现有测试文件动态生成测试任务。假设您有各种以模式命名的单元测试文件test_.rb.所以我正在做的是创建一个以“测试”命名空间内的文件名命名的任务。使用下面的代码,我可以用raketest:调用所有测试require'rake/testtask'task:default=>'test:all'namespace:testdodesc"Runalltests"Rake::TestTask.new(:all)do|t|t.test_files=FileList['test_*.rb']endFileList['test_*.rb'].eachdo|task|n
根据thispostbyStephenHagemann,我正在尝试为我的一个rake任务编写Rspec测试.lib/tasks/retry.rake:namespace:retrydotask:message,[:message_id]=>[:environment]do|t,args|TextMessage.new.resend!(args[:message_id])endendspec/tasks/retry_spec.rb:require'rails_helper'require'rake'describe'retrynamespaceraketask'dodescribe're