The priority keyword controls the sequence of rule execution.
This keyword is a rule header property that is used to control the order in which rules are executed depending on their priority.
Rule properties
priority = {expression};
A rule header can contain a property priority. The priority is an integer expression. If you do not specify any value, the default priority value is 0.
The priority of a rule determines its position in the agenda. The priority can be static or dynamic.
You use a static priority to change the sequence of rule execution among different rules. Static priorities are any integer between -109 and +109. The larger the number, the higher the execution priority of the rule.
Rules with the same priority are processed according to the order in which they are added to the rule engine agenda. Rules more recently inserted into the agenda are chosen before the less recently inserted. Rules inserted at the same time appear in the agenda in the same order as they do in the ruleset source file.
You use a dynamic priority to change the order of execution when the agenda contains several instances of the same rule. Dynamic priorities are expressions. The value of a dynamic priority depends on variables defined in the condition part of a rule. You can use any global variables (whose scope is for the entire rule) in a dynamic priority expression. If the expression returns a non-integer, this non-integer is converted into an integer according the Java™ language specification.
The first example shows a static priority defined as an integer. The second example shows a dynamic priority based on a variable.
rule StaticExample {
priority = 1,000,000;
when ...
then ...
}
The StaticExample rule has a static priority value of 1,000,000. Therefore, it will be listed in the agenda before the rules with a priority lower than 1,000,000.
rule ActiveStockByChange{
priority = ?c;
when {
?s:Stock(?p:currentPrice; ?l:lastClosingPrice;
?c = (?p-?l)/?l);
}
then {
System.out.println(?s.symbol +" : price: "+ ?p +
" change: "+ ?c);
}
The ActiveStockByChange rule has a dynamic priority equal to the percent change of the stock price. For all the Stock objects of this class, the order of rule execution will depend on the change in price. The larger the positive change, the earlier the rule will be executed. The larger the negative change, the later the rule will be executed.