• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

无信不立

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

【java规则引擎】《Drools7.0.0.Final规则引擎教程》第4章 4.3 日历

日历

日历可以单独应用于规则中,也可以和timer结合使用在规则中使用。通过属性calendars来定义日历。如果是多个日历,则不同日历之间用逗号进行分割。

在Drools中,日历的概念只是将日历属性所选择的时间映射成布尔值,设置为规则的属性,控制规则的触发。Drools可以通过计算当期日期和时间来决定是否允许规则的触发。 
此示例首先需要引入quarts框架:

<dependency>
    <groupId>org.opensymphony.quartz</groupId>
    <artifactId>quartz</artifactId>
    <version>1.6.1</version>
</dependency>
View Code

实现Quarts的Calendar转换为Drools的Calendar的转换器CalendarWrapper:

public class CalendarWrapper implements Calendar{

    private WeeklyCalendar cal;

    public CalendarWrapper(WeeklyCalendar cal) {
        this.cal = cal;
    }

    @Override
    public boolean isTimeIncluded(long timestamp) {
        return cal.isTimeIncluded(timestamp);
    }

    public WeeklyCalendar getCal() {
        return cal;
    }

    public void setCal(WeeklyCalendar cal) {
        this.cal = cal;
    }

}
View Code

规则文件:

package com.rules

rule "calenderTest"

    calendars "weekday"
//    timer (int:0 1s) // 可以和timer配合使用

    when
        str : String();
    then
        System.out.println("In rule - " + drools.getRule().getName());
        System.out.println("String matched " + str);
    end
View Code

测试方法:

@Test
    public void timerTest() throws InterruptedException {

        final KieSession kieSession = createKnowledgeSession();

        WeeklyCalendar weekDayCal = new WeeklyCalendar();
        // 默认包含所有的日期都生效
        weekDayCal.setDaysExcluded(new boolean[]{false, false, false, false, false, false, false,false,false});
//        weekDayCal.setDayExcluded(java.util.Calendar.THURSDAY, true); // 设置为true则不包含此天,周四
        Calendar calendar = new CalendarWrapper(weekDayCal);

        kieSession.getCalendars().set("weekday", calendar);

        kieSession.insert(new String("Hello"));
        kieSession.fireAllRules();

        kieSession.dispose();
        System.out.println("Bye");
}

protected KieSession createKnowledgeSession() {
        KieServices kieServices = KieServices.Factory.get();
        KieSessionConfiguration conf = kieServices.newKieSessionConfiguration();

        KieContainer kieContainer = kieServices.getKieClasspathContainer();
        KieSession kSession = kieContainer.newKieSession("ksession-rule", conf);
        return kSession;
 }
View Code

执行测试方法打印结果:

In rule - calenderTest
String matched Hello
Bye
View Code

其中测试过程中的注意点已经在代码中进行标注,比如Calendar可以和timer共同使用;如何设置WeeklyCalendar中哪一天执行,哪一天不执行。

posted on 2018-08-07 20:44  无信不立  阅读(229)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3