사용자 지정 트리거 만들기(예 2)

이 예는 지정된 간격으로 실행할 태스크를 만들 수 있는 Automation 360에서 트리거를 생성하는 방법을 보여줍니다.

특정 조건이 충족되면 트리거가 Bot를 시작하고 조건이 변경되거나 중지될 때까지 대기합니다. 트리거 조건이 일치하면 실행 방법을 호출하여 트리거에 신호를 보냅니다.

필요한 주석 기호

트리거를 생성하려면 다음 주석 기호가 필요합니다.

주석 기호 사용량
BotCommand BotCommand 주석 기호와 함께 트리거commandType로 사용합니다. 이렇게 하면 플레인 구형 Java 객체(POJO)가 Automation 360와 트리거 생성에 적합합니다.
CommandPkg 이러한 값은 패키지를 생성할 때 사용됩니다. 주석 기호에 이름, 라벨 및 설명을 입력합니다.
TriggerId 트리거를 중지하는 데 필요한 트리거 ID입니다.

TriggerConsumer

트리거 조건이 충족될 때 호출할 소비자 함수를 지정합니다.
StartListen 트리거 수신기를 시작합니다.
StopAllTriggers 모든 트리거를 취소하는 데 사용되는 메소드를 식별합니다.
StopListen 특정 트리거를 취소하는 메소드를 식별합니다.

유스케이스 - 타이머 트리거

다음 유스케이스는 Bot를 일정한 간격으로 트리거하는 타이머 트리거를 생성하는 방법을 보여줍니다. 여기에 설명된 Demo Trigger 명령 샘플은 사용자가 지정한 간격에 따라 트리거를 생성하고 관리할 수 있는 트리거 명령입니다. 이 트리거는 일정한 간격으로 태스크를 실행하는 데 사용할 수 있습니다.

명령 정보
@BotCommand(commandType = BotCommand.CommandType.Trigger)
@CommandPkg(label = "Demo Trigger", description = "Demo Trigger", icon = "email.svg", name = "demoTrigger",
      return_type = RECORD, return_name = "TriggerData", return_description = "Available keys: triggerType")
  • 명령 유형: 트리거
  • 라벨: 데모 트리거
  • 설명: 데모 트리거
  • 아이콘: email.svg
  • 이름: demoTrigger
  • 반환 유형: 기록
  • 반환 이름: TriggerData
  • 반환 설명: 사용 가능한 키: triggerType
클래스 구조

TriggerDemo 클래스는 트리거 태스크를 관리하는 싱글톤 클래스입니다. triggerId를 키로 사용하여 맵에 태스크를 저장합니다. 트리거 조건이 충족되면 연관된 Runnablerun 메소드가 호출되어 트리거를 알립니다.

Class 변수
  • taskMap: 여러 트리거 태스크를 저장하는 정적 ConcurrentHashMap입니다.
  • TIMER: 트리거 태스크를 예약하는 데 사용되는 정적 Timer입니다.
  • triggerUid: @TriggerId로 주석을 추가하고 트리거의 고유 식별자를 나타냅니다.
  • consumer: @TriggerConsumer로 주석을 추가하고 트리거 데이터를 승인할 소비자입니다.
메소드
  • startTrigger: @StartListen으로 주석을 추가하고 이 메소드가 트리거를 시작합니다. 트리거 활성화 간격을 지정하는 데는 간격 매개변수(초)가 필요합니다. 실행될 때 연결된 Runnablerun 메소드를 호출하는 새 TimerTask>를 생성합니다. TimerTask는 triggerUid를 키로 사용하여 taskMap에 추가되며 지정된 간격으로 실행되도록 예약됩니다.
  • getRecordValue: 트리거 데이터를 포함하는 RecordValue를 생성하고 반환하는 비공개 메소드입니다. 트리거 데이터에는 단일 키 "triggerType"과 해당 값 "Interval Trigger"가 있는 스키마가 포함됩니다.
  • stopAllTriggers: @StopAllTriggers로 주석을 추가하고 이 메소드는 모든 트리거 태스크를 취소하고 taskMap을 지웁니다.
  • stopListen: @StopListen으로 주석을 추가하고 이 메소드는 triggerUid 매개변수로 식별된 특정 트리거 태스크를 취소하고 taskMap에서 해당 태스크를 제거합니다.
  • 세터 메소드: setTriggerUidsetConsumer는 각각 triggerUidconsumer 변수에 대한 세터 메소드입니다.
/*
 * Copyright (c) 2023 Automation Anywhere.
 * All rights reserved.
 *
 * This software is the proprietary information of Automation Anywhere.
 * You shall use it only in accordance with the terms of the license agreement
 * you entered into with Automation Anywhere.
 */

/**
 * 
 */
package com.automationanywhere.botcommand.samples.trigger;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;

import com.automationanywhere.botcommand.data.Value;
import com.automationanywhere.botcommand.data.impl.RecordValue;
import com.automationanywhere.botcommand.data.impl.StringValue;
import com.automationanywhere.botcommand.data.model.Schema;
import com.automationanywhere.botcommand.data.model.record.Record;
import com.automationanywhere.commandsdk.annotations.*;
import com.automationanywhere.commandsdk.annotations.rules.GreaterThan;
import com.automationanywhere.commandsdk.annotations.rules.NotEmpty;
import com.automationanywhere.commandsdk.annotations.rules.NumberInteger;
import com.automationanywhere.commandsdk.model.AttributeType;
import com.automationanywhere.commandsdk.model.DataType;

import static com.automationanywhere.commandsdk.model.DataType.RECORD;

/**
 * There will be a singleton instance of this class. Whenever a new trigger is
 * created it comes with a triggerId. In this sample we create multiple tasks
 * and store them in a map with these triggerId as the key. Once the condition
 * of trigger matches we call the run method of the runnable to signal the
 * trigger.
 * In the following example we will create a trigger which triggers are user
 * specified intervals.
 *
 */
@BotCommand(commandType = BotCommand.CommandType.Trigger)
@CommandPkg(label = "Demo Trigger", description = "Demo Trigger", icon = "email.svg", name = "demoTrigger",
		return_type = RECORD, return_name = "TriggerData", return_description = "Available keys: triggerType")
public class TriggerDemo {

	// Map storing multiple tasks
	private static final Map<String, TimerTask> taskMap = new ConcurrentHashMap<>();
	private static final Timer TIMER = new Timer(true);

	@TriggerId
	private String triggerUid;
	@TriggerConsumer
	private Consumer consumer;

	/*
	 * Starts the trigger.
	 */
	@StartListen
	public void startTrigger(@Idx(index = "1", type = AttributeType.NUMBER)
	@Pkg(label = "Please provide the interval to trigger in seconds", default_value = "120", default_value_type = DataType.NUMBER)
	@GreaterThan("0")
	@NumberInteger
	@NotEmpty
	Double interval) {
		TimerTask timerTask = new TimerTask() {

			@Override
			public void run() {
				consumer.accept(getRecordValue());
			}
		};

		taskMap.put(this.triggerUid, timerTask);
		TIMER.schedule(timerTask, interval.longValue());
	}

	private RecordValue getRecordValue() {
		List<Schema> schemas = new LinkedList<>();
		List<Value> values = new LinkedList<>();
		schemas.add(new Schema("triggerType"));
		values.add(new StringValue("Interval Trigger"));

		RecordValue recordValue = new RecordValue();
		recordValue.set(new Record(schemas,values));
		return recordValue;
	}

	/*
	 * Cancel all the task and clear the map.
	 */
	@StopAllTriggers
	public void stopAllTriggers() {
		taskMap.forEach((k, v) ->  {
			if (v.cancel()) {
				taskMap.remove(k);
			}
		});
	}

	/*
	 * Cancel the task and remove from map
	 *
	 * @param triggerUid
	 */
	@StopListen
	public void stopListen(String triggerUid) {
		if (taskMap.get(triggerUid).cancel()) {
			taskMap.remove(triggerUid);
		}
	}

	public void setTriggerUid(String triggerUid) {
		this.triggerUid = triggerUid;
	}

	public void setConsumer(Consumer consumer) {
		this.consumer = consumer;
	}

}
다음은 Demo Trigger를 사용하는 예제입니다.
demoTrigger.startTrigger(60.0);

이렇게 하면 60초마다 실행되는 트리거가 시작되고 트리거 데이터로 연결된 소비자에게 호출됩니다.

트리거를 중지하려면 다음 메소드를 사용할 수 있습니다.

  • demoTrigger.stopAllTriggers(): 이 메소드는 모든 활성 트리거를 중지합니다.
  • demoTrigger.stopListen(triggerUid): 이 메소드는 triggerUid에서 식별된 특정 트리거를 중지합니다.
    주: triggerUid는 각 트리거의 고유 식별자이며 트리거가 생성될 때 자동으로 할당됩니다.