Drools Fusion中的计时器无法正常工作

时间:2014-01-06 06:26:15

标签: drools drools-fusion

我试图在Drool Fusion(版本5.4.1)中运行以下规则,但它不起作用。

理想情况下,它应该每7秒打印一次“HELLO WORLD”,它甚至不会触发一次。

有人可以帮我理解Drools中的计时器吗?

     import com.drools.message.Message

rule "Test" 
    timer(int: 7s 7s)
when
    message:Message (type=="Hello")
then
    System.out.println("Hello World, Drools! " + message.getMsgtext());
end
   My code to run the above Rule is:
public class TestDrools {

  private static String DRL_FILE = "test_drools.drl";
  private static KnowledgeBuilder kbuilder = KnowledgeBuilderFactory
          .newKnowledgeBuilder();
  private static Collection pkgs;
  private static KnowledgeBase kbase = KnowledgeBaseFactory
          .newKnowledgeBase();
  private static StatefulKnowledgeSession ksession;

  private static WorkingMemoryEntryPoint entryPoint;

  public static void main(String[] args) {
      init();
      while (true) {
          Message msg = new Message();
          msg.setType("Hello");
          msg.setMsgtext("1");
          ksession.insert(msg);
      }
  }

  private static void init() {
      initialiseDrools();
  }

  private static void initialiseDrools() {
      kbuilder.add(ResourceFactory.newClassPathResource(DRL_FILE),
              ResourceType.DRL);
      if (kbuilder.hasErrors()) {
          System.out.println(kbuilder.getErrors().toString());
          throw new RuntimeException("Unable to compile drl\".");
      }
      pkgs = kbuilder.getKnowledgePackages();
      KnowledgeBaseConfiguration config = KnowledgeBaseFactory
              .newKnowledgeBaseConfiguration();
      config.setOption(EventProcessingOption.STREAM);
      kbase = KnowledgeBaseFactory.newKnowledgeBase(config);
      kbase.addKnowledgePackages(pkgs);
      KnowledgeSessionConfiguration conf = KnowledgeBaseFactory
              .newKnowledgeSessionConfiguration();
      conf.setOption(ClockTypeOption.get("pseudo"));
      ksession = kbase.newStatefulKnowledgeSession(conf, null);
      entryPoint = ksession.getWorkingMemoryEntryPoint("entryone");
      new Thread() {
          @Override
          public void run() {
              ksession.fireUntilHalt();
          }
      }.start();
  }
}

谢谢 -Sanjay

2 个答案:

答案 0 :(得分:1)

根据@ laune的评论,您使用了pseudo clock。如果要使用realtime时钟,请更改以下行:

  conf.setOption(ClockTypeOption.get("realtime"));

或者只是完全删除该行 - realtime是默认时钟。

如果你想使用伪时钟,你需要自己推进它。这通常用于单元测试,例如

  SessionPseudoClock  clock = ksession.getSessionClock();
  // insert some facts ... 
  clock.advanceTime(1, TimeUnit.HOURS);
  ksession().fireAllRules();

  // Do your unit test asserts / verify mocks here to verify that 
  // time-reasoned rules were / weren't fired

答案 1 :(得分:0)

then条件满足时会发生

when条件,因此您需要至少将eval(true)放入when condition并触发插入knowledgeSession,以便规则引擎弄清楚当某些条件满足时该怎么做。