Timers

Timers can be used to wait for a predefined amount of time, before triggering. They could be used to specify timeout behaviour, to trigger certain logic after a certain period or repeat it at regular intervals.

A timer needs to specify a delay and a period. The delay specifies the amount of time (in milliseconds) to wait after activation before triggering the timer the first time. The period defines the time between subsequent activations. If the period is 0, the timer will only be triggered once.

The timer service is responsible for making sure that timers get triggered at the appropriate times. Timers can also be cancelled, meaning that the timer will no longer be triggered.

Timers can be used in two ways inside a process:

By default, the Drools engine is a passive component, meaning that it will only start processing if you tell it to (for example, you first insert the necessary data and then tell the engine to start processing). In passive mode, a timer that has been triggered will be put on the action queue. This means that it will be executed the next time the engine is told to start executing by the user (using fireAllRules() or if the engine is already / still running), in which case the timer will be executed automatically.

When using timers, it does usually make sense to make the Drools engine an active component, meaning that it will execute actions whenever they become available (and not wait until the user tells it to start executing again). This would mean a timer would be executed once it is triggered. To make the engine fire all actions continuously, you must call the fireUntilHalt() method. That means the engine will continue firing until the engine is halted. The following fragment shows how to do this (note that you should call fireUntilHalt() in a separate thread as it will only return if the engine has been halted (by either the user or some logic calling halt() on the session):

new Thread(new Runnable() {
  public void run() {
    ksession.fireUntilHalt();
  }
}).start();

// starting a new process instance
ksession.startProcess("...");
// any timer that will trigger will now be executed automatically