use of io.camunda.zeebe.client.api.worker.JobWorker in project zeebe-test-container by camunda-community-hub.
the class TriggerTimerCatchEventTest method shouldTriggerTimerStartEvent.
@Test
@Timeout(value = 5, unit = TimeUnit.MINUTES)
void shouldTriggerTimerStartEvent() {
// given
final ZeebeClock clock = ZeebeClock.newDefaultClock(zeebeContainer);
final BpmnModelInstance process = Bpmn.createExecutableProcess("process").startEvent().intermediateCatchEvent().timerWithDate(TIMER_DATE.toString()).serviceTask("task", b -> b.zeebeJobType(JOB_TYPE)).endEvent().done();
final List<ActivatedJob> activatedJobs = new CopyOnWriteArrayList<>();
final Instant brokerTime;
// when
final JobHandler handler = (client, job) -> activatedJobs.add(job);
try (final ZeebeClient client = newZeebeClient(zeebeContainer);
final JobWorker worker = newJobWorker(handler, client)) {
client.newDeployCommand().addProcessModel(process, "process.bpmn").send().join();
client.newCreateInstanceCommand().bpmnProcessId("process").latestVersion().send().join();
brokerTime = clock.addTime(TIME_OFFSET);
Awaitility.await("until a job has been activated by the worker").untilAsserted(() -> Assertions.assertThat(activatedJobs).hasSize(1));
}
// then
Assertions.assertThat(activatedJobs).as("the timer event was triggered and a job is now available").hasSize(1);
Assertions.assertThat(brokerTime).as("the modified time is at least equal to one day from now").isAfterOrEqualTo(TIMER_DATE);
}
use of io.camunda.zeebe.client.api.worker.JobWorker in project zeebe by camunda.
the class JobWorkerCreator method main.
public static void main(final String[] args) {
final String defaultAddress = "localhost:26500";
final String envVarAddress = System.getenv("ZEEBE_ADDRESS");
final ZeebeClientBuilder clientBuilder;
if (envVarAddress != null) {
/* Connect to Camunda Cloud Cluster, assumes that credentials are set in environment variables.
* See JavaDoc on class level for details
*/
clientBuilder = ZeebeClient.newClientBuilder().gatewayAddress(envVarAddress);
} else {
// connect to local deployment; assumes that authentication is disabled
clientBuilder = ZeebeClient.newClientBuilder().gatewayAddress(defaultAddress).usePlaintext();
}
final String jobType = "foo";
try (final ZeebeClient client = clientBuilder.build()) {
System.out.println("Opening job worker.");
try (final JobWorker workerRegistration = client.newWorker().jobType(jobType).handler(new ExampleJobHandler()).timeout(Duration.ofSeconds(10)).open()) {
System.out.println("Job worker opened and receiving jobs.");
// run until System.in receives exit command
waitUntilSystemInput("exit");
}
}
}
use of io.camunda.zeebe.client.api.worker.JobWorker in project zeebe by zeebe-io.
the class WorkloadGenerator method performSampleWorkload.
/**
* Given a client, deploy a process, start instances, work on service tasks, create and resolve
* incidents and finish the instance.
*/
public static void performSampleWorkload(final ZeebeClient client) {
client.newDeployResourceCommand().addProcessModel(SAMPLE_PROCESS, "sample_process.bpmn").send().join();
final Map<String, Object> variables = new HashMap<>();
variables.put("orderId", "foo-bar-123");
variables.put("largeValue", "x".repeat(8192));
variables.put("unicode", "Á");
variables.put("nullable", null);
final long processInstanceKey = client.newCreateInstanceCommand().bpmnProcessId("testProcess").latestVersion().variables(variables).send().join().getProcessInstanceKey();
// create job worker which fails on first try and sets retries to 0 to create an incident
final AtomicBoolean fail = new AtomicBoolean(true);
final JobWorker worker = client.newWorker().jobType("work").handler((handlerClient, job) -> {
if (fail.getAndSet(false)) {
// fail job
handlerClient.newFailCommand(job.getKey()).retries(0).errorMessage("failed").send().join();
} else {
handlerClient.newCompleteCommand(job.getKey()).send().join();
}
}).open();
client.newPublishMessageCommand().messageName("catch").correlationKey("foo-bar-123").send().join();
// wait for incident and resolve it
final Record<IncidentRecordValue> incident = Awaitility.await("the incident was created").timeout(Duration.ofMinutes(1)).until(() -> RecordingExporter.incidentRecords(IncidentIntent.CREATED).withProcessInstanceKey(processInstanceKey).withElementId("task").findFirst(), Optional::isPresent).orElseThrow();
client.newUpdateRetriesCommand(incident.getValue().getJobKey()).retries(3).send().join();
client.newResolveIncidentCommand(incident.getKey()).send().join();
// wrap up
Awaitility.await("the process instance was completed").timeout(Duration.ofMinutes(1)).until(() -> RecordingExporter.processInstanceRecords(ProcessInstanceIntent.ELEMENT_COMPLETED).filter(r -> r.getKey() == processInstanceKey).exists());
worker.close();
}
use of io.camunda.zeebe.client.api.worker.JobWorker in project zeebe by zeebe-io.
the class JobWorkerCreator method main.
public static void main(final String[] args) {
final String defaultAddress = "localhost:26500";
final String envVarAddress = System.getenv("ZEEBE_ADDRESS");
final ZeebeClientBuilder clientBuilder;
if (envVarAddress != null) {
/* Connect to Camunda Cloud Cluster, assumes that credentials are set in environment variables.
* See JavaDoc on class level for details
*/
clientBuilder = ZeebeClient.newClientBuilder().gatewayAddress(envVarAddress);
} else {
// connect to local deployment; assumes that authentication is disabled
clientBuilder = ZeebeClient.newClientBuilder().gatewayAddress(defaultAddress).usePlaintext();
}
final String jobType = "foo";
try (final ZeebeClient client = clientBuilder.build()) {
System.out.println("Opening job worker.");
try (final JobWorker workerRegistration = client.newWorker().jobType(jobType).handler(new ExampleJobHandler()).timeout(Duration.ofSeconds(10)).open()) {
System.out.println("Job worker opened and receiving jobs.");
// run until System.in receives exit command
waitUntilSystemInput("exit");
}
}
}
use of io.camunda.zeebe.client.api.worker.JobWorker in project zeebe by camunda-cloud.
the class Worker method run.
@Override
public void run() {
final WorkerCfg workerCfg = appCfg.getWorker();
final String jobType = workerCfg.getJobType();
final long completionDelay = workerCfg.getCompletionDelay().toMillis();
final var variables = readVariables(workerCfg.getPayloadPath());
final BlockingQueue<Future<?>> requestFutures = new ArrayBlockingQueue<>(10_000);
final BlockingDeque<DelayedCommand> delayedCommands = new LinkedBlockingDeque<>(10_000);
final ZeebeClient client = createZeebeClient();
printTopology(client);
final JobWorker worker = client.newWorker().jobType(jobType).handler((jobClient, job) -> {
final var command = jobClient.newCompleteCommand(job.getKey()).variables(variables);
if (workerCfg.isCompleteJobsAsync()) {
delayedCommands.addLast(new DelayedCommand(Instant.now().plusMillis(completionDelay), command));
} else {
try {
Thread.sleep(completionDelay);
} catch (Exception e) {
e.printStackTrace();
}
requestFutures.add(command.send());
}
}).open();
final ResponseChecker responseChecker = new ResponseChecker(requestFutures);
responseChecker.start();
final var asyncJobCompleter = new DelayedCommandSender(delayedCommands, requestFutures);
if (workerCfg.isCompleteJobsAsync()) {
asyncJobCompleter.start();
}
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
worker.close();
client.close();
asyncJobCompleter.close();
responseChecker.close();
}));
}
Aggregations