6

Is there any way I can get back the Integer value updated in Drools rule. I am passing the string in my rule. I can see my rule running but I am not getting the updated global variable's value. Here is my Drools rule file :

import com.MessageType;

global java.lang.Integer delayInSeconds;

rule "Delay for Update"
when 
String(this == MessageType.UPDATE.getType())
then
System.out.println("Running delay rule.....");
delayInSeconds = 10;
update(delayInSeconds); // This gives me runtime error. If I remove it I dont get error but dont get updated value.
end

I have also tried this : kcontext.getKieRuntime().setGlobal("delayInSeconds" , 10); but no luck :(

I know I can pass this variable by setting in POJO. So just wanted to confirm if there is any way by we can get updated value using global Integer. Please suggest.

rishi
  • 1,792
  • 5
  • 31
  • 63

3 Answers3

7

Global variables are a different species. You can read them, you can use them almost (!) like plain old variables, but:

Any update of a global variable must be done via the API method KieRuntime.setGlobal().

In your rule, you could use

drools.setGlobal( delayInSeconds, Integer.valueOf(10) );

You cannot use update with a global - it is not a fact. Also, rules will not react to a change of a global. Use a fact if you need this.

laune
  • 31,114
  • 3
  • 29
  • 42
  • Thanks for the answer. I just used this kcontext.getKnowledgeRuntime().setGlobal("delay , 10"); I was accessing the variable directly. I had to use kSession.getGlobal("delay "). – rishi Dec 01 '16 at 13:43
  • how to make global into a fact? What is the different? – BabyishTank Mar 23 '23 at 20:55
6

For me this worked

drools.getKnowledgeRuntime().setGlobal(String, Object);

Eg.

drools.getKnowledgeRuntime().setGlobal("delayInSeconds", Integer.valueOf(10));

Shivansh Gaur
  • 918
  • 9
  • 11
  • Or, more precisely, when using the above in the RHS of a rule: the String is a string representation of your global variable, while Object is it's new value.
    E.g.:
    `drools.getKnowledgeRuntime().setGlobal("loopCounter", Integer.valueOf(loopCounter + 1));`
    – Tihamer Jun 22 '18 at 18:05
1

You can use.

then
   System.out.println("Running delay rule.....");  
   delayInSeconds = "whatever calculations";
   drools.getKnowledgeRuntime().setGlobal("delayInSeconds", delayInSeconds);
end
Pranith Baggan
  • 104
  • 1
  • 7