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. 总结baiduTemplate和djangoTemplate的学习

    引入      开发工作中需要,除了今天要介绍的两种template,还有很多模板,但他们的终点都是相同的,都是为了开发的便利.       模板的作用       是一套模板语法,开发者可以通过写一 ...

  2. hibernate(八) Hibernate检索策略(类级别,关联级别,批量检索)详解

    序言 很多看起来很难的东西其实并不难,关键是看自己是否花费了时间和精力去看,如果一个东西你能看得懂,同样的,别人也能看得懂,体现不出和别人的差距,所以当你觉得自己看了很多书或者学了很多东西的时候,你要 ...

  3. hibernate(三) 一对多映射关系

    序言 前面两节讲了hibernate的两个配置文件和hello world!.还有hibernate的一级缓存和三种状态,基本上hibernate就懂一点了,从这章起开始一个很重要的知识点,hiber ...

  4. 快速入门系列--NOSQL--05Redis也木有那么“高富帅”

    由于工作慢慢从原来的少量用户的企业内部应用慢慢转化为了大量用户的企业内部应用或者直接转为了线上高并发应用,因而也渐渐的开始使用memcached.Redis等缓存服务器,为了便于自身的学习和记忆,特此 ...

  5. Javaweb -- ServletContextListener

    当启动web应用后端服务时,有时需要预先从数据库或者配置文件等读取信息来配置一些全局变量之类的 这时可以用ServletContextListener,在启动服务时,加载设置基本配置 实现如下: (1 ...

  6. [Qt5] Develop openCV3 by QML on Qt-creator

    QML的酷炫控件,适合移动设备开发. qt-creator的跨平台是QML与opencv的粘合剂. 关键: QImage有若干种格式,转化为相应的Mat. Mat处理完后,还要正确得还原为原来格式的Q ...

  7. Android 软键盘弹出时把原来布局顶上去的解决方法

    键盘弹出时,会将布局底部的导航条顶上去. 解决办法: 在mainfest.xml中,在和导航栏相关的activity中加: <activity            android:name=& ...

  8. SQL SERVER 内存分配及常见内存问题 简介

    一.问题: 1.SQL Server 所占用内存数量从启动以后就不断地增加: 首先,作为成熟的产品,内存溢出的机会微乎其微.对此要了解SQL SERVER与windows是如何协调.共享内存.并且SQ ...

  9. C++程序设计之四书五经[转自2004程序员杂志]--上篇

    C++程序设计之四书五经 作者:荣耀 C++是一门广泛用于工业软件研发的大型语言.它自身的复杂性和解决现实问题的能力,使其极具学术研究价值和工业价值.和C语言一样,C++已经在许多重要的领域大获成功. ...

  10. Elasticsearch聚合 之 Date Histogram聚合

    Elasticsearch的聚合主要分成两大类:metric和bucket,2.0中新增了pipeline还没有研究.本篇还是来介绍Bucket聚合中的常用聚合--date histogram.参考: ...