Was asynchronous jobs removed from the Play framework? What is a better alternative?

試著忘記壹切 提交于 2019-11-28 05:47:12

问题


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?

I saw some samples where people create a Global class, but not entirely sure if/how I should use that to replace Job.

Any suggestions?

Edit: If you gonna downvote, give a reason. Maybe I'm missing something in the question, maybe this doesn't belong here. At least something...


回答1:


The Job class was removed in Play 2.0.

You have some alternatives though depending on your Play version and if you need asynchrony or not:

Akka Actors

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()
           );
      }  
 }

See https://www.playframework.com/documentation/2.3.x/JavaAkka for details.

Eager Singletons

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();
    }
}

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");
    }
}

See https://www.playframework.com/documentation/2.4.x/JavaDependencyInjection#Eager-bindings



来源:https://stackoverflow.com/questions/31007478/was-asynchronous-jobs-removed-from-the-play-framework-what-is-a-better-alternat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!