Drools文档提到规则可以使用属性,如date-effective
和date-expires
来指定绝对规则有效期。
例如
rule "Date-restricted rule"
date-effective "20.2.2013 8:00" # 8 AM
date-expires "20.2.2013 16:00" # 4 PM
when
then
end
Drools 还支持使用间隔 astimer(int:)
和 cron as定期重复timer(cron:)
的规则,但这意味着在这些点触发规则。
问题:
如果有任何选项如何指定具有时间限制的定期可用(未触发)规则,我很感兴趣。例如,让我们想象一些公司的营业时间 - 只能在正式工作期间进行操作,但不能在下班后进行。
我想要这样的东西,但这不是 Drools 的有效规则
rule "Time-restricted rule"
time-effective "8:00" # 8 AM
time-expires "16:00" # 4 PM
when
then
end
是否可以将此类规则扩展为仅在周一至周五上午 8 点至下午 4 点有效?
解决方案(由 Esteban Aliverti 提供):
Drools 不直接支持基于时间的关键字,但它们使用Quartz库提供了更强大的日历机制。StatefulSession
或WorkingMemory
由StatelessSession
具有定义这些日历的方法创建,这些日历可以限制可以触发规则的日期和时间。
示例: 规则定义
rule "Business hours only"
calendars "business-hours"
when
SomeAttachedClass()
then
System.out.println("Rule is fired");
end
日历定义
import org.quartz.impl.calendar.DailyCalendar;
// stateless session and working memory or directly stateful session
StatefulKnowledgeSession memory = session.newWorkingMemory();
// interested time range is 8-16, also there is many Calendar implementation, not just Daily
DailyCalendar businessHours = new DailyCalendar( 8, 0, 0, 0, 16, 0, 0, 0 );
// by default, defined time is EXCLUDED, the inversion makes it INCLUDED and excludes the rest
businessHours.setInvertTimeRange( true );
//convert the calendar into a org.drools.time.Calendar
org.drools.time.Calendar businessHoursCalendar = QuartzHelper.quartzCalendarAdapter( businessHours );
//Register the calendar in the session with a name. You must use this name in your rules.
memory.getCalendars().set( "business-hours", businessHoursCalendar );