Execute Drools rule at certain time or fact

十年热恋 提交于 2020-04-30 10:56:55

问题


I'd like a rule to fire when it's 8am OR the sun is up. How to go about this?

rule X
    when
        ( "it's 8am" and ... and ...)
        or
        (Sun( up ) and ... and ...)
    then
        // do something
end

A timer acts like a prerequisite. So I guess it's not useful in this case.

An extra time fact would have to be updated every second, which would cause the rule to refire every second. I guess I could split the time fact into hour, minute, and second facts, but that wouldn't really solve the problem, but only make it occur less often.

Is such a rule possible/viable in Drools?


回答1:


You could have a rule that is constantly keeping track of the time. Then your rule can just check for that time to fire. I used milliseconds for simplicity sake, but I think you can see how it can be adapted to whatever you want. To solve your firing issue every second issue, adapt the Time class to use Calendar objects or something along those lines. Just initialize your knowledge session with a Time object.

rule "update time"
   when
        $time : Time(value != currentTime)
    then
        modify($time){
            setValue($time.getCurrentTime());
        };
end

rule "X"
     when
        Time(value = //whatever time)
     then
     // do something
end


public class Time
{
     long value;

     public Time()
     {
          value = getCurrentTime();
     }

     //getter and setter for value

     public long getCurrentTime()
     {
          return System.currentTimeMilliSeconds();
     }

}



回答2:


So this is what I do to have time as an extra trigger:

1) Create a separate rule based solely on a cron trigger, which inserts a time-fact at 8am.

2) Have the actual rule check for the cron-triggered time fact.

rule "08:00 AM"
    timer( cron: 0 0 8 * * ? )
    when // empty
    then
        insertLogical( new Time(31) ); // 31 is a rule ID, see below
end

rule "X"
    when
        Time( ruleID == 31 )
        or
        Sun( up )
    then
        // do something
end

insertLogical inserts a fact into memory and removes it when it's no longer needed. This is the time fact:

public class Time {
    private int ruleID;

    public Time( int ruleID ) {
        this.ruleID = ruleID;
    }

    public getRuleID() {
        return this.ruleID;
    }
}


来源:https://stackoverflow.com/questions/16845777/execute-drools-rule-at-certain-time-or-fact

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!