Create a ProcessEngine

  • The configuration file for the Activiti process engine is an XML file named Activiti.cfg.xml. Note that this is not the same as creating a process engine using Spring
  • Using org. Activiti. Engine. ProcessEngines class, get the ProcessEngine:
ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine()
Copy the code

It searches activiti.cfg.xml under classpath and builds the engine based on the configuration in that file

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration">

    <property name="jdbcUrl" value="jdbc:h2:mem:activiti; DB_CLOSE_DELAY=1000" />
    <property name="jdbcDriver" value="org.h2.Driver" />
    <property name="jdbcUsername" value="sa" />
    <property name="jdbcPassword" value="" />

    <property name="databaseSchemaUpdate" value="true" />

    <property name="jobExecutorActivate" value="false" />

    <property name="mailServerHost" value="mail.my-corp.com" />
    <property name="mailServerPort" value="5025" />
  </bean>

</beans>
Copy the code

ProcessEngineConfiguration used in the configuration file can be created programmatically, you can configure different bean id

ProcessEngineConfiguration.createProcessEngineConfigurationFromResourceDefault();
ProcessEngineConfiguration.createProcessEngineConfigurationFromResource(String resource);
ProcessEngineConfiguration.createProcessEngineConfigurationFromResource(String resource, String beanName);	// Configure a different bean ID
ProcessEngineConfiguration.createProcessEngineConfigurationFromInputStream(InputStream inputStream);
ProcessEngineConfiguration.createProcessEngineConfigurationFromInputStream(InputStream inputStream, String beanName);
Copy the code

If you do not use a configuration file for configuration, the configuration is created based on the default

  • ProcessEngineConfiguration. CreateXXX () method will return to the ProcessEngineConfiguration, follow-up can be adjusted to the desired object. After calling buildProcessEngine(), a ProcessEngine is created:
  ProcessEngine processEngine = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration()
  .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_FALSE)
  .setJdbcUrl("jdbc:h2:mem:my-own-db; DB_CLOSE_DELAY=1000")
  .setJobExecutorActivate(true)
  .buildProcessEngine();
Copy the code

ProcessEngineConfiguration bean

  • Activiti. CFG. XML must contain an id = ‘processEngineConfiguration’ bean
 <bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration">
Copy the code

The bean will be used to construct ProcessEngine. There are multiple classes can be used to define the processEngineConfiguration. These classes correspond to different environments and set the corresponding default values:

  • Org. Activiti. Engine. Impl. CFG. StandaloneProcessEngineConfiguration: separate operation of the process engine. Activiti handles the transaction itself. The default database is only detected at engine startup (an exception will be thrown if there is no Activiti table or if the table structure is incorrect)
  • Org. Activiti. Engine. Impl. CFG. StandaloneInMemProcessEngineConfiguration: auxiliary class unit test. Activiti controls the transaction itself. The H2 in-memory database is used by default, and the database tables are created when the engine is started and deleted when the engine is shut down. No additional configuration is required to use it (unless you use the Job executor or the mail function)
  • Org. Activiti. Spring. SpringProcessEngineConfiguration: in a spring environment using the process engine
  • Org. Activiti. Engine. Impl. CFG. JtaProcessEngineConfiguration: separate process engine operation, and use the JTA transaction

Database Configuration

Define database configuration parameters

  • Defines database connection configuration based on database configuration parameters
    • JdbcUrl: the JDBC URL of the database
    • JdbcDriver: drivers corresponding to different database types
    • JdbcUsername: user name for connecting to the database
    • JdbcPassword: indicates the password for connecting to the database
  • The default MyBatis connection pool will be used for database connections based on JDBC parameter configuration.
    • JdbcMaxActiveConnections: connection pool is in a state by using the maximum number of connections. The default is 10
    • JdbcMaxIdleConnections: the maximum number of idle connections in the connection pool
    • JdbcMaxCheckoutTime: The maximum time for a connection to be taken out, which will be forcibly reclaimed. Default is 20000(20 seconds)
    • JdbcMaxWaitTime: This is an underlying configuration that allows the connection pool to print a log and retry to obtain a connection if it has been unavailable for a long time (to avoid silent operation failures due to misconfiguration) default 20000(20 seconds)

Use javax.sql.DataSource configuration

  • These classes are not included in the Activiti distribution, so put them in your CLASspath
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" >
  <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <property name="url" value="jdbc:mysql://localhost:3306/activiti" />
  <property name="username" value="activiti" />
  <property name="password" value="activiti" />
  <property name="defaultAutoCommit" value="false" />
</bean>

<bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration">

    <property name="dataSource" ref="dataSource" />.</bean>
Copy the code
  • Using either JDBC or DataSource, you can set the following configuration:
    • databaseType:
      • This is generally not required because it is automatically retrieved from the metadata of the database connection
      • This parameter is required only when automatic detection fails. The possible values are: {h2, mysql, oracle, postgres, MSSQL, db2}
      • You must set this if you are not using the default H2 database. This configuration determines which create/delete scripts and query statements to use
    • databaseSchemaUpdate:Set how database tables are handled when the process engine is started and shut down
      • False: By default, check the version of the database table and the version of the dependent library, and throw an exception if the version does not match
      • True: When building the process engine, perform checks and updates if necessary. If the table does not exist, create it
      • Create-drop: Database tables are created when the process engine is built and dropped when the process engine is shut down

JNDI database configuration

  • By default,Activiti’s database configuration is placed in the db.properties file in the WEB-INF/classes directory of the Web application. This is cumbersome because it requires the user to either modify the db.properties in Activiti’s source code and recompile the WAR file, or unzip the WAR file and change the DB.properties in it at each release
  • Use JNDI(Java Naming and Directory Interface) to get the database connection, which is managed by the Servlet container and can manage the configuration outside of the WAR deployment. It also allows for more configuration of connections than db.properties

The use of JNDI

  • Activiti Explorer and Activiti Rest applications convert from db.properties to use JNDI database configuration:
    • You need to open the original Spring configuration file:
      • activiti-webapp-explorer/src/main/webapp/WEB-INF/activiti-standalone-context.xml
      • activiti-webapp-rest2/src/main/resources/activiti-context.xml
    • Delete the dbProperties and dataSource beans and add the following beans:
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/activitiDB"/>
</bean>
Copy the code
  • We need to add the context.xml file that contains the default H2 configuration
  • If you already have JNDI configurations, they are overwritten. The corresponding configuration file activiti – webapp – explorer2 / SRC/main/webapp/meta-inf/context. The XML:

      
<Context antiJARLocking="true" path="/activiti-explorer2">
    <Resource auth="Container"
              name="jdbc/activitiDB"
              type="javax.sql.DataSource"
              scope="Shareable"
              description="JDBC DataSource"
              url="jdbc:h2:mem:activiti; DB_CLOSE_DELAY=1000"
              driverClassName="org.h2.Driver"
              username="sa"
              password=""
              defaultAutoCommit="false"
              initialSize="5"
              maxWait="5000"
              maxActive="120"
              maxIdle="5"/>
</Context>
Copy the code
  • If the Activiti REST application, then add Activiti – webapp – rest2 / SRC/main/webapp/meta-inf/context. XML:

      
<Context antiJARLocking="true" path="/activiti-rest2">
    <Resource auth="Container"
              name="jdbc/activitiDB"
              type="javax.sql.DataSource"
              scope="Shareable"
              description="JDBC DataSource"
              url="jdbc:h2:mem:activiti; DB_CLOSE_DELAY=-1"
              driverClassName="org.h2.Driver"
              username="sa"
              password=""
              defaultAutoCommit="false"
              initialSize="5"
              maxWait="5000"
              maxActive="120"
              maxIdle="5"/>
</Context>
Copy the code
  • Finally, delete the db.properties files that are no longer used in the Activiti Explorer and Activiti Rest applications

The configuration of the JNDI

  • The JNDI database configuration varies depending on which Servlet Container is used
  • The JNDI configuration in the Tomcat container is as follows:
    • JNDI resources are configured in CATALINA_BASE/conf/[enginename]/[hostname]/[warName].xml(for Activiti) Explorer, usually in CATALINA_BASE/conf/Catalina/localhost/activiti – Explorer. War) published for the first time, when the application will copy the files from the war. So if the file already exists, you need to replace it. Modify the JNDI resources to make the application connect to mysql instead of H2:

      
    <Context antiJARLocking="true" path="/activiti-explorer2">
        <Resource auth="Container"
            name="jdbc/activitiDB"
            type="javax.sql.DataSource"
            description="JDBC DataSource"
            url="jdbc:mysql://localhost:3306/activiti"
            driverClassName="com.mysql.jdbc.Driver"
            username="sa"
            password=""
            defaultAutoCommit="false"
            initialSize="5"
            maxWait="5000"
            maxActive="120"
            maxIdle="5"/>
    </Context>
Copy the code

Activiti supported databases

  • H2: default configured database
  • mysql
  • oracle
  • postgres
  • db2
  • mssql

Create a database table

  • Create a database table:
    • The JAR for activiti-Engine is placed in the classpath
    • Add the corresponding database driver
    • Put the Activiti configuration file (Activiti.cfg.xml) in your classpath and point it to your database
    • Execute the main method of DbSchemaCreate class
SQL DDL statements can be found on the Activiti download page or in the Activiti distribution directory, under the Database subdirectory. The activiti-engle-x. jar file is also included in the engine jar: activiti-engle-x. jar In the org/activiti/db/create directory, the drop directory is the delete statement -sql file named as follows: [activiti. {db}. {create | drop}. {type}. The SQL] type is: - engine: engine perform table, must - identity: contain the user, group, the relationship between the users and groups tables. These tables are optional and are required only when the default identity management provided by the engine is used. -history: A table containing history and audit information is optional. Not used when the history level is set to None. Note that this also references some functionality that needs to be saved to the history tableCopy the code

Database table name understanding

  • Activiti tables all begin with **ACT_**, and the second part is a two-letter identifier that indicates the purpose of the table. The purpose corresponds to the SERVICE API
    • ACT_RE_*: RE stands for repository. This prefixed table contains process definitions and process static resources
    • ACT_RU_*: RU stands for runtime. These are run-time tables that contain running data for process instances, tasks, variables, asynchronous tasks, and so on. Activiti saves this data only during the process instance execution and deletes the records at the end of the process. This way the table can stay very small and very fast at runtime
    • ACT_ID_*: ID stands for identity. These tables contain identity information. Users, groups, and so on
    • ACT_HI_*: HI stands for history. These tables contain historical data. Examples include historical process instances, variables, tasks, and so on
    • ACT_GE_*: common data. Used in different scenarios

Database Upgrade

  • Use the database backup function to back up the database before performing updates
  • By default, version checking is done every time a process engine is built. This all happens when the app starts or Activiti WebApp starts. If Activiti finds that the version of the database table is different from that of the dependent library, it throws an exception
  • Configure the activiti.cfg.xml configuration file to upgrade:
<beans . >

  <bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration">
    <! -... -->
    <property name="databaseSchemaUpdate" value="true" />
    <! -... -->
  </bean>

</beans>
Copy the code
  • Then, put the corresponding database driver in the CLASspath. Upgrade your application’s Activiti dependencies. Start a new version of Activiti pointing to the database containing the old version, set databaseSchemaUpdate to true, and Activiti will automatically upgrade the database tables to the new version
  • When the versions of dependencies and database tables are inconsistent, you can also execute update update DDL statements
  • You can also execute database scripts, which can be found on the Activiti download page

Example Enable the Job actuator

  • JobExecutor is a component that manages a series of threads that trigger timers (including subsequent asynchronous messages).
  • It is difficult to use multithreading in a unit test scenario. So the query API allows the Job (ManagementService createJobQuery) and perform the Job (ManagementService. ExecuteJob),
  • So the Job can be controlled in unit tests, and to avoid conflicts with the Job executor, you can turn it off
  • By default,JobExecutor is activated when the process engine starts. If you do not want to automatically activate JobExecutor after the process engine starts, set this parameter
<property name="jobExecutorActivate" value="false" />
Copy the code

Configuring the Mail Server

  • Activiti supports sending mail within a business process, and you can configure the mail server in the configuration
  • Configure the SMTP mail server to send mails

Configuring historical Storage

  • Activiti can be configured to customize historical storage information
<property name="history" value="audit" />
Copy the code

Expressions and scripts expose configuration

  • By default, all beans in activiti.cfg.xml and Spring configuration files can be used in expressions and scripts
  • If you want to limit the visibility of beans in a configuration file, you can do so by configuring beans configured by the process engine
  • ProcessEngineConfiguration beans is a map. * * when specifying the parameters, only contain the bean in the map can be used in expressions and scripts. * * by the name of the specified in the map to determine the exposure of the bean

Configuring deployment Caching

  • Because the data for the process definition does not change, all the process definitions are cached after parsing to avoid using the database every time
  • By default, this cache is not limited. If you want to limit the process definition cache, you can add the following configuration
<property name="processDefinitionCacheLimit" value="10" />
Copy the code

This configuration replaces the default HashMap cache with an LRU cache to provide constraints. The optimal value for this configuration depends on the total number of process definitions and how many process definitions are actually used

  • Can also be injected into a custom cache implementation, the bean must implement org. Activiti. Engine. The impl. Persistence. Deploy. DeploymentCache interface
<property name="processDefinitionCache">
  <bean class="org.activiti.MyCache" />
</property>
Copy the code
  • Similar configurations are knowledgeBaseCacheLimit and knowledgeBaseCache, which configure rule caching. Only used when rule tasks are used in the process

The log

  • Starting with Activiti 5.12, all logs (Activiti, Spring, Mybatis, etc.) are forwarded to SLF4J to allow custom logging implementations
  • The introduction of Maven to rely on log4j implementation requires version addition
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-log4j12</artifactId>
</dependency>
Copy the code
  • Using Maven examples, ignore versions
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>jcl-over-slf4j</artifactId>
</dependency>
Copy the code

Mapping diagnostic context

  • Activiti supports SLF4JMDCThe following basic information will be recorded in the log:
    • Process definition ID: mdcProcessDefinitionID
    • Process instance ID: mdcProcessInstanceID
    • Branch ID: mdcexecutionId
  • This information is not logged by default, and logs can be configured to display it in the desired format, extending the usual log information. For example, the log4j configuration definition would make the log display the following information:
 log4j.appender.consoleAppender.layout.ConversionPattern =ProcessDefinitionId=%X{mdcProcessDefinitionID}
executionId=%X{mdcExecutionId}mdcProcessInstanceID=%X{mdcProcessInstanceID} mdcBusinessKey=%X{mdcBusinessKey} %m%n"
Copy the code

This feature is very useful when the system is performing high-risk tasks and the logs must be rigorously checked to use the log analysis case

The event processing

  • An event mechanism is implemented in Activiti that allows you to be alerted when an event is triggered by the engine
  • Register listeners for the corresponding event type and receive alerts whenever this type is fired:
    • Engine-wide event listeners can be added, and the API can be configured to add engine-wide event listeners at run time
    • Add an event-Listener to the BPMN XML defined by the specific process
  • All events, distribution is org. Activiti engine. The delegate. Event. ActivitiEvent subclass. Event contains the type, executionId processInstanceId and processDefinitionId. The corresponding event contains additional information about the context in which the event occurred

Event listener implementation

  • Implement event listener to achieve org. Activiti. Engine. Delegate. Event. ActivitiEventListener.
  • The following listener implementation prints all monitored events to standard output, including job execution exceptions:
public class MyEventListener implements ActivitiEventListener {

  @Override
  public void onEvent(ActivitiEvent event) {
    switch (event.getType()) {

      case JOB_EXECUTION_SUCCESS:
        System.out.println("A job well done!");
        break;

      case JOB_EXECUTION_FAILURE:
        System.out.println("A job has failed...");
        break;

      default:
        System.out.println("Event received: "+ event.getType()); }}@Override
  public boolean isFailOnException(a) {
    // The logic in the onEvent method of this listener is not critical, exceptions
    // can be ignored if logging fails...
    return false; }}Copy the code

IsFailOnException (): Determines onEvent(..) when the event is dispatched. Method to throw an exception

  • Returns false, the exception is ignored
  • Returns true, the exception is not ignored and propagates upwards, rapidly causing the current command to fail
  • When the event is part of an API call (or other transactional operation, such as job execution), the transaction is rolled back
  • It is recommended to return false when the behavior in the event listener is not business
  • Activiti provides some basic implementations that implement common scenarios for event listeners that can be used as examples for base class or listener implementations
    • org.activiti.engine.delegate.event.BaseEntityEventListener:
      • The base class of this event listener can be used to listen for entity-related events, either for one type of entity or for all entities
      • Type detection is hidden and three methods need to be overridden:
        • onCreate(..)
        • onUpdate(..)
        • onDelete(..)
        • Called when an entity is created, updated, or deleted
      • For other entity-related events, onEntityEvent(..) is called.

Configuration installation of event listeners

  • Event listeners configured into the process engine configuration are activated when the process engine is started and continue to work during engine startup
  • eventListenersAttribute toorg.activiti.engine.delegate.event.ActivitiEventListenerThe queue
    • In general, we can declare an internal bean definition or use a ref to reference a defined bean. The following code adds an event listener to the configuration to alert it when any event is triggered, no matter what type:
<bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration">.<property name="eventListeners">
      <list>
         <bean class="org.activiti.engine.example.MyEventListener" />
      </list>
    </property>
</bean>
Copy the code
  • To listen for specific types of events
    • TypedEventListeners properties can be used
    • It takes a map parameter
    • Map keys are comma-separated event names or individual event names
    • The value of the map is org. Activiti. Engine. Delegate. Event. ActivitiEventListener queue
  • The following code demonstrates adding an event listener to the configuration to listen for job success or failure:
<bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration">.<property name="typedEventListeners">
      <map>
        <entry key="JOB_EXECUTION_SUCCESS,JOB_EXECUTION_FAILURE" >
          <list>
            <bean class="org.activiti.engine.example.MyJobEventListener" />
          </list>
        </entry>
      </map>
    </property>
</bean>
Copy the code

The order in which events are distributed is determined by the order in which listeners are added

  • First, all the normal eventListeners properties are called in the order in which they are listed on the list
  • All typedEventListeners are then called and events of the corresponding type are triggered

Add listeners at run time

  • Additional event listeners are added or removed at run time via the API:RuntimeService:
/**
 * Adds an event-listener which will be notified of ALL events by the dispatcher.
 * @param listenerToAdd the listener to add
 */
void addEventListener(ActivitiEventListener listenerToAdd);

/**
 * Adds an event-listener which will only be notified when an event occurs, which type is in the given types.
 * @param listenerToAdd the listener to add
 * @param types types of events the listener should be notified for
 */
void addEventListener(ActivitiEventListener listenerToAdd, ActivitiEventType... types);

/**
 * Removes the given listener from this dispatcher. The listener will no longer be notified,
 * regardless of the type(s) it was registered for in the first place.
 * @param listenerToRemove listener to remove
 */
 void removeEventListener(ActivitiEventListener listenerToRemove);
Copy the code
  • The listener engine added during run time disappears after restart

The process definition adds listeners

  • Add listeners for specific process definitions:
    • Listeners only listen for events related to the process definition and for all process instances initiated on the process definition
  • Listener implementation:
    • You can define it using the full class name
    • Reference to an expression that implements the listener interface
    • Configure to throw a MESSAGE, Signal,error BPMN event
Listeners perform custom logic
  • The following code adds two listeners to a process definition:
    • The first listener, which receives all types of events, is defined by the full class name
    • The second listener, which receives only job success or failure events, uses a bean defined in the Beans property in the process engine configuration
<process id="testEventListeners">
  <extensionElements>
    <activiti:eventListener class="org.activiti.engine.test.MyEventListener" />
    <activiti:eventListener delegateExpression="${testEventListener}" events="JOB_EXECUTION_SUCCESS,JOB_EXECUTION_FAILURE" />
  </extensionElements>.</process>
Copy the code
  • For entity-related events, it can also be set to a listener for a process definition, so that the implementation listens only for a type of entity event that occurs on a process definition. The following code shows how to do this:
    • First example: to listen for all entity events
    • Second example: for listening for a specific type of event
<process id="testEventListeners">
  <extensionElements>
    <activiti:eventListener class="org.activiti.engine.test.MyEventListener" entityType="task" />
    <activiti:eventListener delegateExpression="${testEventListener}" events="ENTITY_CREATED" entityType="task" />
  </extensionElements>.</process>
Copy the code
  • EntityType supports the following values:
    • attachment
    • comment
    • execution
    • identity-link
    • job
    • process-instance
    • process-definition
    • task
Listen for BPMN events thrown
  • Another way to handle events isThrows a BPMN event:
    • A BPMN event is thrown only for BPMN events of type Activiti that are thrown, resulting in an error when the process instance is deleted
  • The following code demonstrates how to throw a signal in a process instance, throw signal to an external process (global), throw a message event in a process instance, and throw an error event in a process instance. In addition to using class or delegateExpression, the throwEvent attribute is also used, with additional attributes that specify the type of event to throw
<process id="testEventListeners">
  <extensionElements>
    <activiti:eventListener throwEvent="signal" signalName="My signal" events="TASK_ASSIGNED" />
  </extensionElements>
</process>
Copy the code
<process id="testEventListeners">
  <extensionElements>
    <activiti:eventListener throwEvent="globalSignal" signalName="My signal" events="TASK_ASSIGNED" />
  </extensionElements>
</process>
Copy the code
<process id="testEventListeners">
  <extensionElements>
    <activiti:eventListener throwEvent="message" messageName="My message" events="TASK_ASSIGNED" />
  </extensionElements>
</process>
Copy the code
<process id="testEventListeners">
  <extensionElements>
    <activiti:eventListener throwEvent="error" errorCode="123" events="TASK_ASSIGNED" />
  </extensionElements>
</process>
Copy the code
  • If you need to declare additional logic, whether to throw BPMN events, you can extend the listener class provided by Activiti:
    • Override in a subclassisValidEvent(ActivitiEvent event),Can prevent BPMN events from being thrown. The corresponding class is:
      • org.activiti.engine.impl.bpmn.helper.MessageThrowingEventListener
      • org.activiti.engine.test.api.event.SignalThrowingEventListenerTest
      • org.activiti.engine.impl.bpmn.helper.ErrorThrowingEventListener
Process definition listener notes
  • Event listeners can only be declared in process elements as children of extensionElements. Listeners cannot be defined under a single activity of the process
  • Unlike other expressions (such as gateway), expressions in delegateExpression do not have access to the execution context. It can only reference beans defined in beans properties declared in the process engine configuration, or use all spring-beans in Spring (without beans properties) that implement listener interfaces
  • When a listener’s class attribute is used, only one instance is created. Listener implementations do not depend on member variables and are multithreaded safe
  • When an invalid event type is used in the Events property or throwEvent, an exception is thrown when the process definition is published (resulting in deployment failure)
    • If class or delegateExecution by problem: Class does not exist, bean reference does not exist, or proxy class does not implement listener interface
      • Throws an exception when the process starts
      • When the first valid process definition event is received by the listener
    • To ensure that the referenced class is placed correctly in the classpath, the expression also needs to reference a valid instance

Distribute events through the API

  • At Activiti we provide a way to use the event mechanism through the API, allowing any custom event defined in the engine to be fired
  • It is recommended that only ActivitiEvents of type CUSTOM be triggered. Events can be triggered by RuntimeService:
/**
 * Dispatches the given event to any listeners that are registered.
 * @param event event to dispatch.
 *
 * @throws ActivitiException if an exception occurs when dispatching the event or when the {@link ActivitiEventDispatcher}
 * is disabled.
 * @throws ActivitiIllegalArgumentException when the given event is not suitable for dispatching.
 */
 void dispatchEvent(ActivitiEvent event);
Copy the code

Supported event types

  • Engine corresponding org. Each event type. Activiti engine. The delegate. Event. One of ActivitiEventType enumeration values
The name of the event Event description The event type
ENGINE_CREATED The process engine that the listener listens to has been created and is ready for the API call ActivitiEvent
ENGINE_CLOSED The process engine that the listener is listening to is closed and no longer accepts API calls ActivitiEvent
ENTITY_CREATED A new entity is created, and the entity is included in the event ActivitiEntityEvent
ENTITY_INITIALIZED A new entity is created and initialization is complete. If the creation of the entity involves the creation of child entities, this event is emitted after all child entities are created/initialized, which is different from ENTITY_CREATED ActivitiEntityEvent
ENTITY_UPDATED Updated an existing entity that is included in the event ActivitiEntityEvent
ENTITY_DELETED Deleted an existing entity that is included in the event ActivitiEntityEvent
ENTITY_SUSPENDED Suspends an existing entity that is included in the event. Will beProcessDefinitions ProcessInstances and Tasksthrow ActivitiEntityEvent
ENTITY_ACTIVATED An existing entity is activated, and the entity is included in the event. Will beProcessDefinitions ProcessInstances and Tasksthrow ActivitiEntityEvent
JOB_EXECUTION_SUCCESS The job is included in the event ActivitiEntityEvent
JOB_EXECUTION_FAILURE Job execution fails and job and exception information is contained in the event ActivitiEntityEvent

ActivitiExceptionEvent
JOB_RETRIES_DECREMENTED The number of retries decreased because the job failed. Procedure Jobs are contained in events ActivitiEntityEvent
TIMER_FIRED The timer is triggered, and the job is included in the event ActivitiEntityEvent
JOB_CANCELED An assignment was canceled. The event contains the canceled job. Jobs can be cancelled by API calls, and the corresponding boundary timer is cancelled when the task is complete, as well as when a new process definition is published ActivitiEntityEvent
ACTIVITY_STARTED A node starts executing ActivitiActivityEvent
ACTIVITY_COMPLETED A node ends successfully. Procedure ActivitiActivityEvent
ACTIVITY_SIGNALED A node receives a signal ActivitiSignalEvent
ACTIVITY_MESSAGE_RECEIVED A node received a message. Procedure Emitted before the node receives the message, and emitted after the node receives the messageACTIVITY_SIGNALorACTIVITY_STARTED,This depends on the node type: boundary event, event subprocess start event ActivitiMessageEvent
ACTIVITY_ERROR_RECEIVED A node received an error event. Procedure Emitted before the node actually handles the erroractivityIdCorresponds to theHandling the wrong node.This event will be followed byACTIVITY_SIGNALLEDorACTIVITY_COMPLETE,If the error is sent successfully ActivitiErrorEvent
UNCAUGHT_BPMN_ERROR An uncaught BPMN error was thrown. The process does not provide a handler for this error.The activityId of the event is empty ActivitiErrorEvent
ACTIVITY_COMPENSATE A node will be compensated. The event contains the ID of the node on which compensation will be performed ActivitiActivityEvent
VARIABLE_CREATED A variable is created. The event contains the variable name, variable value, and corresponding branch or task (if one exists) ActivitiVariableEvent
VARIABLE_UPDATED A variable was updated. The event contains the variable name, variable value, and corresponding branch or task (if one exists) ActivitiVariableEvent
VARIABLE_DELETED A variable was deleted. The event contains the variable name, variable value, and corresponding branch or task (if one exists) ActivitiVariableEvent
TASK_ASSIGNED The task was assigned to a person. Event containment task ActivitiEntityEvent
TASK_CREATED A new task is created. It is locatedENTITY_CREATEWhen the task is created by the process, this event is displayed in theTaskListenerBeing executed before being executed ActivitiEntityEvent
TASK_COMPLETED Mission complete. it will be inENTITY_DELETEWhen the task is part of the process, the event is preceded by **ACTIVITY_COMPLETE, which corresponds to the node that completed the task, before the process continues ActivitiEntityEvent
TASK_TIMEOUT The task has timed out. YesTIMER_FIREDEvent triggers a timeout event for the user task when a timer is assigned to the task ActivitiEntityEvent
PROCESS_COMPLETED The process has ended. On the last nodeACTIVITY_COMPLETEDEvent. The process ends when it reaches a state where there are no further connections ActivitiEntityEvent
MEMBERSHIP_CREATED A user is added to a group. The event contains user and group ids ActivitiMembershipEvent
MEMBERSHIP_DELETED The user is deleted from a group. The event contains user and group ids ActivitiMembershipEvent
MEMBERSHIPS_DELETED All members are removed from a group. This event is triggered before members are deleted, so they are all accessible. For performance reasons, a separate MEMBERSHIP_DELETED event is not triggered for each member ActivitiMembershipEvent
  • Everything inside the engineENTITY_* Events are related to entities, and the corresponding relationship between entity events and entities:
    • [ENTITY_CREATED],[ENTITY_INITIALIZED],[ENTITY_DELETED]:
      • Attachment
      • Comment
      • Deployment
      • Execution
      • Group
      • IdentityLink
      • Job
      • Model
      • ProcessDefinition
      • ProcessInstance
      • Task
      • User
    • ENTITY_UPDATED:
      • Attachment
      • Deployment
      • Execution
      • Group
      • IdentityLink
      • Job
      • Model
      • ProcessDefinition
      • ProcessInstance
      • Task
      • User
    • ENTITY_SUSPENDED, ENTITY_ACTIVATED:
      • ProcessDefinition
      • ProcessInstance
      • Execution
      • Task

Pay attention to

  • Only events in the same process engine are sent to the corresponding listener
  • If there are many engines running in the same database, events are only sent to listeners registered with the corresponding engine. Events from other engines are not sent to this listener, regardless of whether they are actually running on the same or different JVM
  • The corresponding event type contains the corresponding entity. Depending on type or event, these entities can no longer be updated (for example, when an instance is deleted). Whenever possible, use the Events provided EngineServices to operate the engine in a safe way. Even so, be careful to update the entity that corresponds to the event
  • There are no historical entity events, because they all have run-time entities