Asynchronous Jobs

Because Play is a web application framework, most of the application logic is done by controllers responding to HTTP requests.

But sometimes you will need to execute some application logic outside of any HTTP request. It can be useful for initialization tasks, maintenance tasks or to run long tasks without blocking the HTTP request execution pool.

Jobs are fully managed by the framework. That means that Play will manage all the database connection stuff, JPA entity manager synchronization and transactions management for you. To create a job you just need to extend the play.jobs.Job super class.

package jobs;

import play.jobs.*;

public class MyJob extends Job {

    public void doJob() {
        // execute some application logic here ...
    }

}

Sometimes you need to create jobs that return a result. You then override the doJobWithResult()method.

package jobs;

import play.jobs.*;

public class MyJob extends Job<String> {

    public String doJobWithResult() {
        // execute some application logic here ...
        return result;
    }

}

Here the use of String is just for the example, of course a job can return any object type.

Bootstrap jobs

Bootstrap jobs are executed by Play at application start time. To mark your job as a bootstrap job you just need to add the @OnApplicationStart annotation.

import play.jobs.*;

@OnApplicationStart
public class Bootstrap extends Job {

    public void doJob() {
        if(Page.count() == 0) {
            new Page("root").save();
            Logger.info("A root page has been created.");
        }
    }

}

You don’t need to return a result. Even if you do it, the result will be lost.

The default is that all jobs annotated with @OnApplicationStart will be executed in sequence. When all jobs are finished, your application is ready to start processing incoming requests.

If you want your jobs to start when your application starts, but you want to start processing incoming requests immediately, you can annotate your job like this: @OnApplicationStart(async=true). Then your job will be started in the background when the application starts. All async jobs will be started at the same time.

Warning

When you run the application in DEV mode, the application waits for the first HTTP request to start. Moreover when you are in DEV mode, the application will sometimes automatically restart when needed.

When you run in PROD mode, the application will start synchronously with the server start.

Scheduled jobs

Scheduled jobs are run periodically by the framework. You can ask Play to run a job at a specific interval using the @Every annotation.

import play.jobs.*;

@Every("1h")
public class Bootstrap extends Job {

    public void doJob() {
        List<User> newUsers = User.find("newAccount = true").fetch();
        for(User user : newUsers) {
            Notifier.sayWelcome(user);
        }
    }

}

If the @Every annotation is not enough you can use the @On annotation to run your jobs using a CRON expression.

import play.jobs.*;

/** Fire at 12pm (noon) every day **/
@On("0 0 12 * * ?")
public class Bootstrap extends Job {

    public void doJob() {
        Logger.info("Maintenance job ...");
        ...
    }

}

Tip

We use the CRON expression parser from the Quartz library.

You don’t need to return a result. Even if you do it, the result will be lost.

Triggering task jobs

You can also trigger a Job at any time to perform a specific task by simply calling now() on a Job instance. Then this job will be run immediately in a non blocking way.

public static void encodeVideo(Long videoId) {
    new VideoEncoder(videoId).now();
    renderText("Encoding started");
}

Calling now() on a Job returns a Promise value that you can use to retrieve the task result once finished.

Continuing the discussion

Let’s see how to combine Jobs with more powerfull Asynchronous programming with HTTP.

时间: 2024-08-29 21:02:25

Asynchronous Jobs的相关文章

HttpWebRequest - Asynchronous Programming Model/Task.Factory.FromAsyc

Posted by Shiv Kumar on 23rd February, 2011 The Asynchronous Programming Model (or APM) has been around since .NET 1.1 and is still (as of .NET 4.0) the best/recommended solution for asynchronous I/O. Many people go down the route of using a multi-th

PP66 EEPPPPMM SSyysstteemm AAddmmiinniissttrraattiioonn GGuuiiddee 16 R1

※★◆●PP66 EEPPPPMM SSyysstteemm AAddmmiinniissttrraattiioonn GGuuiiddee 16 R1AApprriill 22001166ContentsPrimavera P6 Administrator Setup Tasks .. 7What's Changed 8Launching the Primavera P6 Administrator 9Launching the Primavera P6 Administrator Local

Spark异步job

What if we want to execute 2 actions concurrently on different RDD’s, Spark actions are always synchronous. Like if we perform two actions one after other they always execute in sequentially like one after other. Let see example 1 2 3 4 val rdd = sc.

Scheduling Jobs with Oracle Scheduler

In this chapter: About Scheduler Objects and Their Naming Creating, Running, and Managing Jobs Creating and Managing Programs to Define Jobs Creating and Managing Schedules to Define Jobs Using Events to Start Jobs Creating and Managing Job Chains Pr

转-Asynchronous bulk transfer using libusb

https://falsinsoft.blogspot.jp/2015/02/asynchronous-bulk-transfer-using-libusb.html The 'linusb' is one of the most used open source library for work with usb devices. It allow to make the basic usb data transfers operation in a little bit easier way

jobs

___________1.嵌入式软件设计师 成都安可信电子股份有限公司 http://jobs.51job.com/chengdu/66797177.html嵌入式软件开发 成都市蕊芯智能科技有限公司 http://jobs.51job.com/chengdu-qyq/73442145.html嵌入式软件工程师 四川优博创信息技术股份有限公司 6000-15000/月 http://jobs.51job.com/chengdu-gxq/64856589.html嵌入式软件工程师 成都国蓉科技有限

Asynchronous Pluggable Protocols 初探

Asynchronous Pluggable Protocols,异步可插入协议,允许开发者创建可插协议处理器,MIME过滤器,以及命名空间处理器工作在微软IE4.0浏览器以及更高版本或者URL moniker中.这涉及到Urlmon.dll动态链接库所公开(输出)的可插协议诸多功能,本文不进行深入的原理讲解,只对它其中之一的应用进行解析,那就是如何将一个应用程序注册为URL协议. 应用场景: tencent协议: 当我们打开"tencent://message/?uin=要链接的QQ号 &qu

Bg, Fg, &, Ctrl-Z – 5 Examples to Manage Unix Background Jobs

When you execute a unix shell-script or command that takes a long time, you can run it as a background job. In this article, let us review how to execute a job in the background, bring a job to the foreground, view all background jobs, and kill a bac

ajax(Asynchronous JavaScript + XML) 技术学习

参考文档:https://developer.mozilla.org/en-US/docs/AJAX 本文进行了大致翻译. Ajax 本身本不是一门技术,而是在2005年由Jesse James Garrett首创的描述为一个"新"途径来应用许多已存在的技术,包括:HTML 或者 XHTML, Cascading Style Sheets, JavaScript, The Document Object Model, XML, XSLT, 和最重要的 XMLHttpRequest ob