【发布时间】:2011-04-26 10:10:51
【问题描述】:
如何配置计划间隔:
@Schedule(persistent=true, minute="*", second="*/5", hour="*")
在应用程序代码之外?
- 如何在 ejb-jar.xml 中配置?
- 我可以在应用程序之外配置它(属性文件的种类)吗?
【问题讨论】:
标签: java java-ee-6 ejb-3.1 schedule
如何配置计划间隔:
@Schedule(persistent=true, minute="*", second="*/5", hour="*")
在应用程序代码之外?
【问题讨论】:
标签: java java-ee-6 ejb-3.1 schedule
以下是部署描述符中的调度示例:
<session>
<ejb-name>MessageService</ejb-name>
<local-bean/>
<ejb-class>ejb.MessageService</ejb-class>
<session-type>Stateless</session-type>
<timer>
<schedule>
<second>0/18</second>
<minute>*</minute>
<hour>*</hour>
</schedule>
<timeout-method>
<method-name>showMessage</method-name>
</timeout-method>
</timer>
</session>
另一种配置定时器的方法是编程调度。
@Singleton
@Startup
public class TimedBean{
@Resource
private TimerService service;
@PostConstruct
public void init(){
ScheduleExpression exp=new ScheduleExpression();
exp.hour("*")
.minute("*")
.second("*/10");
service.createCalendarTimer(exp);
}
@Timeout
public void timeOut(){
System.out.println(new Date());
System.out.println("time out");
}
}
【讨论】:
<session-type>Stateless</session-type> 更改为 <session-type>Singleton</session-type>
根据 EJB 3.1 规范,可以通过注解或通过ejb-jar.xml 部署描述符来配置自动计时器。
18.2.2 自动创建计时器
定时器服务支持 自动创建一个基于 bean 类中的元数据或 部署描述符。这允许 bean 开发人员安排一个计时器 不依赖 bean 调用 以编程方式调用其中一个 Timer 服务定时器的创建方法。 自动创建的计时器是 结果由容器创建 应用程序部署。
我对部署描述符 XLM 架构的理解是,您使用 <session> 元素内的 <timer> 元素来定义它。
<xsd:element name="timer"
type="javaee:timerType"
minOccurs="0"
maxOccurs="unbounded"/>
请参阅timerType 复杂类型的定义了解详细信息(尤其是schedule 和timeout-method 元素)。
【讨论】:
对我来说,ejb-jar.xml 变体仅在 TomEE 上开始工作,我在超时方法中传递 javax.ejb.Timer 参数:
<session>
<ejb-name>AppTimerService</ejb-name>
<ejb-class>my.app.AppTimerService</ejb-class>
<session-type>Singleton</session-type>
<timer>
<schedule>
<second>*/10</second>
<minute>*</minute>
<hour>*</hour>
</schedule>
<timeout-method>
<method-name>timeout</method-name>
<method-params>
<method-param>javax.ejb.Timer</method-param>
</method-params>
</timeout-method>
</timer>
public class AppTimerService {
public void timeout(Timer timer) {
System.out.println("[in timeout method]");
}
}
感谢https://blogs.oracle.com/arungupta/entry/totd_146_understanding_the_ejb 发帖。
您可以读取 .properties 文件并以编程方式创建计时器
ScheduleExpression schedule = new ScheduleExpression();
schedule.hour(hourProperty);//previously read property from .properties file
schedule.minute(minuteProperty);//previously read property from .properties file
Timer timer = timerService.createCalendarTimer(schedule);
但我找不到我们可以在 EJB 中使用 cron 表达式。
【讨论】: