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 ...
随机推荐
- 最先进的开源游戏引擎KlayGE 4.3发布
转载请注明出处为KlayGE游戏引擎,本文的永久链接为http://www.klayge.org/?p=2536 经过KlayGE团队半年来的努力,今天KlayGE 4.3正式发布了!在这个版本的开发 ...
- python--基础学习(三)字符串单引号、双引号、三引号
1.基本认识 单引号字符串:'python' 双引号字符串:"python" 三引号字符串:'''python'''(三单引号),"""python& ...
- Android TextView高级特性使用
TextView一般都是用来显示一段文本,这里说的高级特性主要是一些我们平常不太常用的属性.包括文字阴影.自定义字体.html嵌入多格式.字体加粗.插入图片.这些特性平时开发APP的时候,可能一般使用 ...
- AngularJs单元测试
这篇文章主要介绍了angularJS中的单元测试实例,本文主要介绍利用Karma和Jasmine来进行ng模块的单元测试,并用Istanbul 来生成代码覆盖率测试报告,需要的朋友们可以参考下,以下 ...
- 基于Metronic的Bootstrap开发框架经验总结(6)--对话框及提示框的处理和优化
在各种Web开发过程中,对话框和提示框的处理是很常见的一种界面处理技术,用得好,可以给用户很好的页面体验,Bootstrap开发也一样,我们往往在页面新增.编辑.查看详细等界面使用弹出对话框层的方式进 ...
- 让你心动的 HTML5 & CSS3 效果【附源码下载】
这里集合的这组 HTML5 & CSS3 效果,有的是网站开发中常用的.实用的功能,有的是先进的 Web 技术的应用演示.不管哪一种,这些案例中的技术都值得我们去探究和学习. 超炫的 HTML ...
- express 框架之session
一.什么是session? 最近在学习node.js 的express框架,接触到了关于session方面的内容.翻阅了一些的博客,学到了不少东西,发现一篇博文讲的很好,概念内容摘抄如下: Sessi ...
- OpenGL的简单研究-开端
一直想要学习的但是没有学习的东西,大学一直在等待这个时间,终于可以闲下来研究一下这个部分的内容了. 计算机图形学,让计算机处理各种图像的东西,里面也存在很多算法和数学知识,很值得研究的一个领域,之前一 ...
- HTML5使用Div标签来实现表格
当支持HTML5时,我们可以使用样式把DIV实现一个表格table. 关键样式语法:display: table,display: table-row,display: table-cell 下面例子 ...
- wcf和web service的区别
1.WebService:严格来说是行业标准,不是技术,使用XML扩展标记语言来表示数据(这个是夸语言和平台的关键).微软的Web服务实现称为ASP.NET Web Service.它使用Soap简单 ...