问题描述
我想使用 Job
以便我可以在应用程序开始时启动它们.现在好像已经完全从 Play 中移除了?
I wanted to use Job
so I can kick them off on the start of application. Now it seems like it has been removed from Play completely?
我看到一些示例,其中人们创建了一个 Global
类,但不完全确定我是否应该/如何使用它来替换 Job
.
I saw some samples where people create a Global
class, but not entirely sure if/how I should use that to replace Job
.
有什么建议吗?
如果你要投反对票,请给出理由.也许我在问题中遗漏了一些东西,也许这不属于这里.至少有一些东西......
If you gonna downvote, give a reason. Maybe I'm missing something in the question, maybe this doesn't belong here. At least something...
推荐答案
Job 类在 Play 2.0 中被移除.
The Job class was removed in Play 2.0.
您有一些替代方案,但取决于您的 Play 版本以及是否需要异步:
You have some alternatives though depending on your Play version and if you need asynchrony or not:
对于 Play 2.0 之后的所有版本,您可以使用 Akka Actors 安排一次异步任务/actor,并在启动时通过 Play Global
类执行它.
For all version since Play 2.0 you can use Akka Actors to schedule an asynchronous task/actor once and execute it on startup via Play Global
class.
public class Global extends GlobalSettings {
@Override
public void onStart(Application app) {
Akka.system().scheduler().scheduleOnce(
Duration.create(10, TimeUnit.MILLISECONDS),
new Runnable() {
public void run() {
// Do startup stuff here
initializationTask();
}
},
Akka.system().dispatcher()
);
}
}
参见 https://www.playframework.com/documentation/2.3.x/JavaAkka详情.
从 Play 2.4 开始,您可以急切地使用 Guice 绑定单例
Starting with Play 2.4 you can eagerly bind singletons with Guice
import com.google.inject.AbstractModule;
import com.google.inject.name.Names;
public class StartupConfigurationModule extends AbstractModule {
protected void configure() {
bind(StartupConfiguration.class)
.to(StartupConfigurationImpl.class)
.asEagerSingleton();
}
}
StartupConfigurationImpl
会在默认构造函数中完成它的工作.
The StartupConfigurationImpl
would have it's work done in the default constructor.
@Singleton
public class StartupConfigurationImpl implements StartupConfiguration {
@Inject
private Logger log;
public StartupConfigurationImpl() {
init();
}
public void init(){
log.info("init");
}
}
见 https://www.playframework.com/documentation/2.4.x/JavaDependencyInjection#热切绑定
这篇关于异步作业是否从 Play 框架中删除?什么是更好的选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!