简体   繁体   English

在特定时间或事实执行Drools规则

[英]Execute Drools rule at certain time or fact

I'd like a rule to fire when it's 8am OR the sun is up. 我想在早上8点或太阳升起时开火。 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? 这样的规则在Drools中是否可行/可行?

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. 要解决每秒问题的触发问题,请调整Time类以使用Calendar对象或沿这些行的某些内容。 Just initialize your knowledge session with a Time object. 只需使用Time对象初始化您的知识会话。

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();
     }

}

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. 1)仅基于cron触发器创建单独的规则,该触发器在上午8点插入时间事实。

2) Have the actual rule check for the cron-triggered time fact. 2)对cron触发的时间事实进行实际规则检查。

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. insertLogical将一个事实插入内存,并在不再需要时将其删除。 This is the time fact: 这是时间的事实:

public class Time {
    private int ruleID;

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM