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.
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 aro ...
- PP66 EEPPPPMM SSyysstteemm AAddmmiinniissttrraattiioonn GGuuiiddee 16 R1
※★◆●PP66 EEPPPPMM SSyysstteemm AAddmmiinniissttrraattiioonn GGuuiiddee 16 R1AApprriill 22001166Conte ...
- 存储那些事儿(一):异构虚拟化一种实现SMIS
1. 背景 企业存储是企业信息系统管理很重要的组成部分.企业存储包含了大量的数据,供大量人使用.对于航空系统和金融系统来说,信息存储就更加重要了. 作为企业信息存储,扩展性是非常重要的,因为现在企业对 ...
- facebook api之Ads Insights API
The Ads Insights API provides API access for reporting and analytics purposes. When exclusively usin ...
- Zero-input latency scheduler: Scheduler Overhaul
Scheduler Overhaul, with contributions from rbyers, sadrul, rjkroege, sievers, epenner, skyostil, br ...
- [.net 面向对象程序设计进阶] (19) 异步(Asynchronous) 使用异步创建快速响应和可伸缩性的应用程序
[.net 面向对象程序设计进阶] (19) 异步(Asynchronous) 使用异步创建快速响应和可伸缩性的应用程序 本节导读: 本节主要说明使用异步进行程序设计的优缺点及如何通过异步编程. 使用 ...
- FIJ Jobs - 150316
Department Vacancies Total Skill Set Experience Language Oracle; OBIEE 3years English Systems Sr. So ...
- linux杀死jobs的正确方法
输入命令:logout 终端显示:There are stopped jobs. 解决方法: 输入命令:jobs 终端显示:[]+ Stopped vim /etc/network/interface ...
- Async/Await - Best Practices in Asynchronous Programming
https://msdn.microsoft.com/en-us/magazine/jj991977.aspx Figure 1 Summary of Asynchronous Programming ...
随机推荐
- Java EE开发平台随手记1
过完春节以来,一直在负责搭建公司的新Java EE开发平台,所谓新平台,其实并不是什么新技术,不过是将目前业界较为流行的框架整合在一起,做一些简单的封装和扩展,让开发人员更加易用. 和之前负责具体的项 ...
- KendoUI系列:DatePicker
1.基本使用 <link href="@Url.Content("~/C ontent/kendo/2014.1.318/kendo.common.min.css" ...
- WPF中实现验证码功能
其实和winform中的实现差不多,只是由于WPF中控件使用的库与winform中的有区别,大体上还是差不多的,直接看代码: 产生验证码的类:ValidCode.cs public class Val ...
- 后端码农谈前端(CSS篇)第四课:选择器补充(伪类与伪元素)
一.伪类: 属性 描述 :active 向被激活的元素添加样式. :focus 向拥有键盘输入焦点的元素添加样式. :hover 当鼠标悬浮在元素上方时,向元素添加样式. :link 向未被访问的链接 ...
- C++智能指针简单剖析
导读 最近在补看<C++ Primer Plus>第六版,这的确是本好书,其中关于智能指针的章节解析的非常清晰,一解我以前的多处困惑.C++面试过程中,很多面试官都喜欢问智能指针相关的问题 ...
- Mybatis之Oracle增删查改示例--转
http://blog.csdn.net/bingjie1217/article/details/21088431?utm_source=tuicool&utm_medium=referral ...
- Android requires compiler compliance level 5.0 or 6.0. Found '1.8' instead. Please use Android Tools>Fix project Properties.
重装操作系统之后,或者破坏了Android的开发环境之后,需要重新配置好Android的开发环境.但是配置好后,导入原有的项目时,报错: Android requires compiler compl ...
- 献给所有从事IT行业拥有梦想的英语渣们
本文适合读者:从小到大英语都不好,如今选择IT行业需要重拾英语追寻梦想的人,英语大神们请绕行.. 目录 一.背景介绍 二.明确学习目标 2.1 英文文法 2.2 词汇量 三.题外话 3.1 关于本文 ...
- web开发者谷歌浏览器常用插件
1.Allow-Control-Allow-Origin 安装此插件解决跨域问题,在本地起服务器可访别的域的数据. 需在Access-Control-Expose-Headers加上Allow- ...
- Android 2.x中使用actionbar - Actionbarsherlock
1. 范例说明 从Android 3.0开始,Android引入了ActoinBar,不得不说3.0之前android的标题栏确实比较丑,并且还没有任何功能. 之前很多应用的顶部栏很多都是仿苹果的,比 ...