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.

Asynchronous Jobs的更多相关文章

  1. HttpWebRequest - Asynchronous Programming Model/Task.Factory.FromAsyc

    Posted by Shiv Kumar on 23rd February, 2011 The Asynchronous Programming Model (or APM) has been aro ...

  2. PP66 EEPPPPMM SSyysstteemm AAddmmiinniissttrraattiioonn GGuuiiddee 16 R1

    ※★◆●PP66 EEPPPPMM SSyysstteemm AAddmmiinniissttrraattiioonn GGuuiiddee 16 R1AApprriill 22001166Conte ...

  3. 存储那些事儿(一):异构虚拟化一种实现SMIS

    1. 背景 企业存储是企业信息系统管理很重要的组成部分.企业存储包含了大量的数据,供大量人使用.对于航空系统和金融系统来说,信息存储就更加重要了. 作为企业信息存储,扩展性是非常重要的,因为现在企业对 ...

  4. facebook api之Ads Insights API

    The Ads Insights API provides API access for reporting and analytics purposes. When exclusively usin ...

  5. Zero-input latency scheduler: Scheduler Overhaul

    Scheduler Overhaul, with contributions from rbyers, sadrul, rjkroege, sievers, epenner, skyostil, br ...

  6. [.net 面向对象程序设计进阶] (19) 异步(Asynchronous) 使用异步创建快速响应和可伸缩性的应用程序

    [.net 面向对象程序设计进阶] (19) 异步(Asynchronous) 使用异步创建快速响应和可伸缩性的应用程序 本节导读: 本节主要说明使用异步进行程序设计的优缺点及如何通过异步编程. 使用 ...

  7. FIJ Jobs - 150316

    Department Vacancies Total Skill Set Experience Language Oracle; OBIEE 3years English Systems Sr. So ...

  8. linux杀死jobs的正确方法

    输入命令:logout 终端显示:There are stopped jobs. 解决方法: 输入命令:jobs 终端显示:[]+ Stopped vim /etc/network/interface ...

  9. Async/Await - Best Practices in Asynchronous Programming

    https://msdn.microsoft.com/en-us/magazine/jj991977.aspx Figure 1 Summary of Asynchronous Programming ...

随机推荐

  1. 使用Connetion的属性RetainSameConnection

    在SSIS的组件中,很多都会连接到数据库进行操作,Connection有一个属性RetainSameConnection,默认值是False,控制着连接的打开和关闭的时机. 1,如果Connectio ...

  2. socket编程的select模型

    在掌握了socket相关的一些函数后,套接字编程还是比较简单的,日常工作中碰到很多的问题就是客户端/服务器模型中,如何让服务端在同一时间高效的处理多个客户端的连接,我们的处理办法可能会是在服务端不停的 ...

  3. opcode的执行

    原文链接:http://www.orlion.ga/1001/ 当.php文件被编译为opcode后,下一步的执行并非是把opcode编译为机器码而是类似于如下的方式执行: while (TRUE)  ...

  4. 轻松自动化---selenium-webdriver(python) (九)

    本节重点: 上传文件 文件上传操作也比较常见功能之一,上传功能没有用到新有方法或函数,关键是思路. 上传过程一般要打开一个本地窗口,从窗口选择本地文件添加.所以,一般会卡在如何操作本地窗口添加上传文件 ...

  5. Network - FTP与SFTP

    FTP --- FTP File Transfer SFTP --- SSH File Transfer 缩写 名称 协议与端口 安全策略 特征描述 守护进程(linux) 应用场景 SFTP SSH ...

  6. 白话Https

    本文试图以通俗易通的方式介绍Https的工作原理,不纠结具体的术语,不考证严格的流程.我相信弄懂了原理之后,到了具体操作和实现的时候,方向就不会错,然后条条大路通罗马.阅读文本需要提前大致了解对称加密 ...

  7. storm坑之---同步问题

    最近在做一个监控系统,用来监控网站上各个业务功能的调用量以及处理时间,以便及时发现问题,及时处理.做这种实时统计处理系统,自然首先想到了storm,于是现学现用,自然遇到了一些坑,而且不少是网上也难以 ...

  8. Elasticsearch入门必备——ES中的字段类型以及常用属性

    使用Elasticsearch时,了解字段的概念,是必不可少的.毕竟无论是es还是传统的数据库,都无法弱化字段的类型. 背景知识 在Es中,字段的类型很关键: 在索引的时候,如果字段第一次出现,会自动 ...

  9. requests模块--python发送http请求

    requests模块 在Python内置模块(urllib.urllib2.httplib)的基础上进行了高度的封装,从而使得Pythoner更好的进行http请求,使用Requests可以轻而易举的 ...

  10. CSS魔法堂:说说Float那个被埋没的志向

    前言  定位系统中第一难理解就是Normal flow,而第二就非Float莫属了,而Float难理解的原因有俩,1. 一开头我们就用错了:2. 它跟Normal flow靠得太近了.本文尝试理清Fl ...