Play Framework: Call Controller/URL from within a Job

◇◆丶佛笑我妖孽 提交于 2020-01-16 07:41:25

问题


I have a job that runs on the hour. I would like to either call a Controller's Action method like this:

public class MyJob extends Job {

    @Override
    public void doJob() throws Exception {
        MyController.someActionMethod();
    }
}

or call a URL directly.

Any ideas if this is possible from within a Job?

If I call a Controller's action method directly, I get this:

NullPointerException occured : null

play.exceptions.JavaExecutionException
    at play.jobs.Job.call(Job.java:155)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:207)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)
Caused by: java.lang.NullPointerException
    at play.classloading.enhancers.ControllersEnhancer$ControllerInstrumentation.isActionCallAllowed(ControllersEnhancer.java:187)
    at controllers.MyController.someActionMethod(MyController.java)
    at fun.job.MyJob.doJob(MyJob.java:10)
    at play.jobs.Job.doJobWithResult(Job.java:50)
    at play.jobs.Job.call(Job.java:146)
    ... 7 more

回答1:


You can use the WS helper class. For example,

HttpResponse response = WS.url("http://www.yahoo.com/").get()
String html = response.getString(); // or...
Document xml = response.getXml();

What you are doing above would try to do a browser redirect to the URL associated with a controller's action, which doesn't make sense from the context of an asynchronous job, where, among other reasons, there is no browser to process the redirect.




回答2:


Why are you trying to do that? Maybe a better way to achieve the same thing is extract the logic executed by the action into a new class/method and than call it in both controller and job.



来源:https://stackoverflow.com/questions/8469126/play-framework-call-controller-url-from-within-a-job

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