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 ...
随机推荐
- ASP.NET常用的SqlDbHelper类
请引用 using System.Data;using System.Data.SqlClient; 两个命名空间. 可以满足常用的数据集,读取多条数据,以及增删改操作 代码: /// <sum ...
- input---checked小问题
想必有很多做前端同学都遇到了这么一个问题. 那就是checkbox.那就是我们通过jquery设置选中的时候,发现checked属性已经设置上去了 但是选中的样式却没有. 我们做一个简单的测试:看下面 ...
- 面向对象tab栏例子分析
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 自引用指针this
C++为成员函数提供了一个名字为this的指针,这个指针称为自引用指针,每当创建一个对象时,系统就把this指针初始化为指向该对象,即this指针的值是当前调用成员函数的对象的起始地址.每当调用一个成 ...
- SQL*Loader之CASE1
最近项目涉及到将文本文件中的数据导入到Oracle数据库中,故研究了下SQL*Loader,官档提供的资料不是很丰富,很多案例中出现的语句在官档中找不到出处.但它提供的案例本身却彰显出了SQL*Loa ...
- MySQL(Navicat)运行.sql文件时报错:[Err] 2006 - MySQL server has gone away 的解决方法
背景: 今天导入一个数据量很大的.sql文件时,报错: 原因: 可能是sql语句过长,超过mysql通信缓存区最大长度. 解决:1. 编辑 MySQL 安装目录下的 my.ini,在最后添加以下内容: ...
- springmvc学习笔记--json--返回json的日期格式问题
(一)输出json数据 springmvc中使用jackson-mapper-asl即可进行json输出,在配置上有几点: 1.使用mvc:annotation-driven 2.在依赖管理中添加ja ...
- orleans/Documentation
福利 奥尔良的主要好处是︰开发人员工作效率,甚至为非专家程序员;和默认的透明可伸缩性与程序员没有特别努力.我们扩大每个下面这些好处. 开发人员的生产力 奥尔良的编程模型通过提供以下关键的抽象. 担保和 ...
- Mac下Vim配置语法高亮
设置终端的字体颜色 如图,打开终端然后,选择偏好设置,再选择描述文件,再窗口左侧可以选择系统配置好的,或者你也可以自定义,最后别忘了把你的配置设置成默认就行 Vim语法高亮设置 只需要找到vimrc配 ...
- html的<!DOCTYPE>标签初窥
<!DOCTYPE>标签必须放在整个html文档的第一行,之后一行就是从<html>标签开始,所有浏览器都支持<!DOCTYPE>标签. <!DOCTYPE& ...