Search in sources :

Example 6 with GlobalTimerService

use of org.jbpm.process.core.timer.impl.GlobalTimerService in project jbpm by kiegroup.

the class TaskDeadlinesServiceImpl method schedule.

public void schedule(long taskId, long deadlineId, long delay, DeadlineType type) {
    Task task = persistenceContext.findTask(taskId);
    String deploymentId = task.getTaskData().getDeploymentId();
    TimerService timerService = TimerServiceRegistry.getInstance().get(deploymentId + TimerServiceRegistry.TIMER_SERVICE_SUFFIX);
    if (timerService != null && timerService instanceof GlobalTimerService) {
        TaskDeadlineJob deadlineJob = new TaskDeadlineJob(taskId, deadlineId, type, deploymentId, task.getTaskData().getProcessInstanceId());
        Trigger trigger = new IntervalTrigger(timerService.getCurrentTime(), null, null, -1, delay, 0, null, null);
        JobHandle handle = timerService.scheduleJob(deadlineJob, new TaskDeadlineJobContext(deadlineJob.getId(), task.getTaskData().getProcessInstanceId(), deploymentId), trigger);
        logger.debug("scheduling timer job for deadline {} and task {}  using timer service {}", deadlineJob.getId(), taskId, timerService);
        jobHandles.put(deadlineJob.getId(), handle);
    } else {
        ScheduledFuture<ScheduledTaskDeadline> scheduled = scheduler.schedule(new ScheduledTaskDeadline(taskId, deadlineId, type, deploymentId, task.getTaskData().getProcessInstanceId()), delay, TimeUnit.MILLISECONDS);
        List<ScheduledFuture<ScheduledTaskDeadline>> knownFutures = null;
        if (type == DeadlineType.START) {
            knownFutures = startScheduledTaskDeadlines.get(taskId);
        } else if (type == DeadlineType.END) {
            knownFutures = endScheduledTaskDeadlines.get(taskId);
        }
        if (knownFutures == null) {
            knownFutures = new CopyOnWriteArrayList<ScheduledFuture<ScheduledTaskDeadline>>();
        }
        knownFutures.add(scheduled);
        if (type == DeadlineType.START) {
            startScheduledTaskDeadlines.put(taskId, knownFutures);
        } else if (type == DeadlineType.END) {
            endScheduledTaskDeadlines.put(taskId, knownFutures);
        }
    }
}
Also used : Task(org.kie.api.task.model.Task) InternalTask(org.kie.internal.task.api.model.InternalTask) GlobalTimerService(org.jbpm.process.core.timer.impl.GlobalTimerService) TimerService(org.drools.core.time.TimerService) IntervalTrigger(org.drools.core.time.impl.IntervalTrigger) ScheduledFuture(java.util.concurrent.ScheduledFuture) JobHandle(org.drools.core.time.JobHandle) IntervalTrigger(org.drools.core.time.impl.IntervalTrigger) Trigger(org.drools.core.time.Trigger) GlobalTimerService(org.jbpm.process.core.timer.impl.GlobalTimerService)

Example 7 with GlobalTimerService

use of org.jbpm.process.core.timer.impl.GlobalTimerService in project jbpm by kiegroup.

the class GlobalQuartzDBTimerServiceTest method testAbortGlobalTestService.

/**
 * Test that illustrates that jobs are persisted and survives server restart
 * and as soon as GlobalTimerService is active jobs are fired and it loads and aborts the
 * process instance to illustrate jobs are properly removed when isntance is aborted
 * NOTE: this test is disabled by default as it requires real db (not in memory)
 * and test to be executed separately each with new jvm process
 */
@Test
@Ignore
public void testAbortGlobalTestService() throws Exception {
    RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder().entityManagerFactory(emf).addAsset(ResourceFactory.newClassPathResource("org/jbpm/test/functional/timer/IntermediateCatchEventTimerCycle3.bpmn2"), ResourceType.BPMN2).addConfiguration("drools.timerService", "org.jbpm.process.core.timer.impl.RegisteredTimerServiceDelegate").get();
    RuntimeManager manger = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
    // build GlobalTimerService instance
    TimerService globalTs = new GlobalTimerService(manger, globalScheduler);
    // and register it in the registry under 'default' key
    TimerServiceRegistry.getInstance().registerTimerService("default", globalTs);
    // prepare listener to assert results
    final List<Long> timerExporations = new ArrayList<Long>();
    ProcessEventListener listener = new DefaultProcessEventListener() {

        @Override
        public void afterNodeLeft(ProcessNodeLeftEvent event) {
            if (event.getNodeInstance().getNodeName().equals("timer")) {
                timerExporations.add(event.getProcessInstance().getId());
            }
        }
    };
    long id = -1;
    Thread.sleep(5000);
    RuntimeEngine runtime = manger.getRuntimeEngine(ProcessInstanceIdContext.get());
    KieSession ksession = runtime.getKieSession();
    ksession.addEventListener(listener);
    ksession.abortProcessInstance(id);
    ProcessInstance processInstance = ksession.getProcessInstance(id);
    assertNull(processInstance);
    // let's wait to ensure no more timers are expired and triggered
    Thread.sleep(3000);
    ksession.dispose();
}
Also used : RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) RuntimeEnvironment(org.kie.api.runtime.manager.RuntimeEnvironment) ProcessEventListener(org.kie.api.event.process.ProcessEventListener) DefaultProcessEventListener(org.kie.api.event.process.DefaultProcessEventListener) NodeLeftCountDownProcessEventListener(org.jbpm.test.listener.NodeLeftCountDownProcessEventListener) RuntimeManager(org.kie.api.runtime.manager.RuntimeManager) AbstractRuntimeManager(org.jbpm.runtime.manager.impl.AbstractRuntimeManager) ArrayList(java.util.ArrayList) GlobalTimerService(org.jbpm.process.core.timer.impl.GlobalTimerService) TimerService(org.drools.core.time.TimerService) DefaultProcessEventListener(org.kie.api.event.process.DefaultProcessEventListener) KieSession(org.kie.api.runtime.KieSession) ProcessInstance(org.kie.api.runtime.process.ProcessInstance) ProcessNodeLeftEvent(org.kie.api.event.process.ProcessNodeLeftEvent) GlobalTimerService(org.jbpm.process.core.timer.impl.GlobalTimerService) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 8 with GlobalTimerService

use of org.jbpm.process.core.timer.impl.GlobalTimerService in project jbpm by kiegroup.

the class GlobalTimerServiceVolumeTest method testRuntimeManagerStrategyWithTimerService.

@Test(timeout = 30000)
public void testRuntimeManagerStrategyWithTimerService() throws Exception {
    // prepare task service with users and groups
    RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
    TaskService taskService = engine.getTaskService();
    Group grouphr = TaskModelProvider.getFactory().newGroup();
    ((InternalOrganizationalEntity) grouphr).setId("HR");
    Group groupadmins = TaskModelProvider.getFactory().newGroup();
    ((InternalOrganizationalEntity) groupadmins).setId("Administrators");
    User mary = TaskModelProvider.getFactory().newUser();
    ((InternalOrganizationalEntity) mary).setId("mary");
    User john = TaskModelProvider.getFactory().newUser();
    ((InternalOrganizationalEntity) john).setId("john");
    User admin = TaskModelProvider.getFactory().newUser();
    ((InternalOrganizationalEntity) admin).setId("Administrator");
    ((InternalTaskService) taskService).addGroup(grouphr);
    ((InternalTaskService) taskService).addGroup(groupadmins);
    ((InternalTaskService) taskService).addUser(mary);
    ((InternalTaskService) taskService).addUser(john);
    ((InternalTaskService) taskService).addUser(admin);
    manager.disposeRuntimeEngine(engine);
    int counter = numberOfProcesses;
    // start processes until oom
    while (counter > 0) {
        new GlobalTimerServiceVolumeTest.StartProcessPerProcessInstanceRunnable(manager).run();
        counter--;
    }
    Collection<TimerJobInstance> timers = null;
    Map<Long, List<GlobalJobHandle>> jobs = null;
    TimerService timerService = TimerServiceRegistry.getInstance().get(manager.getIdentifier() + TimerServiceRegistry.TIMER_SERVICE_SUFFIX);
    if (timerService != null) {
        if (timerService instanceof GlobalTimerService) {
            jobs = ((GlobalTimerService) timerService).getTimerJobsPerSession();
            timers = ((GlobalTimerService) timerService).getTimerJobFactoryManager().getTimerJobInstances();
        }
    }
    assertNotNull("Jobs should not be null as number of timers have been created", jobs);
    assertEquals("There should be no jobs in the global timer service", 0, jobs.size());
    assertNotNull("Timer instances should not be null as number of timers have been created", timers);
    assertEquals("There should be no timer instances in the global timer service manager", 0, timers.size());
    RuntimeEngine empty = manager.getRuntimeEngine(EmptyContext.get());
    AuditService logService = empty.getAuditService();
    List<? extends ProcessInstanceLog> logs = logService.findActiveProcessInstances("IntermediateCatchEvent");
    assertEquals("Active process instances should be " + numberOfProcesses, numberOfProcesses, logs.size());
    countDownListener.waitTillCompleted();
    List<TaskSummary> tasks = empty.getTaskService().getTasksAssignedAsPotentialOwner("john", "en-UK");
    assertEquals("Number of John's tasks should be " + numberOfProcesses, numberOfProcesses, tasks.size());
    for (TaskSummary task : tasks) {
        RuntimeEngine piEngine = manager.getRuntimeEngine(ProcessInstanceIdContext.get(task.getProcessInstanceId()));
        piEngine.getTaskService().start(task.getId(), "john");
        piEngine.getTaskService().complete(task.getId(), "john", null);
        manager.disposeRuntimeEngine(piEngine);
    }
    logs = logService.findActiveProcessInstances("IntermediateCatchEvent");
    assertEquals("Active process instances should be 0", 0, logs.size());
    logService.dispose();
    manager.disposeRuntimeEngine(empty);
}
Also used : Group(org.kie.api.task.model.Group) RuntimeEngine(org.kie.api.runtime.manager.RuntimeEngine) User(org.kie.api.task.model.User) TimerJobInstance(org.drools.core.time.impl.TimerJobInstance) InternalTaskService(org.kie.internal.task.api.InternalTaskService) TaskService(org.kie.api.task.TaskService) InternalTaskService(org.kie.internal.task.api.InternalTaskService) InternalOrganizationalEntity(org.kie.internal.task.api.model.InternalOrganizationalEntity) GlobalTimerService(org.jbpm.process.core.timer.impl.GlobalTimerService) TimerService(org.drools.core.time.TimerService) TaskSummary(org.kie.api.task.model.TaskSummary) List(java.util.List) ArrayList(java.util.ArrayList) AuditService(org.kie.api.runtime.manager.audit.AuditService) GlobalTimerService(org.jbpm.process.core.timer.impl.GlobalTimerService) Test(org.junit.Test)

Example 9 with GlobalTimerService

use of org.jbpm.process.core.timer.impl.GlobalTimerService in project jbpm by kiegroup.

the class TaskDeadlinesServiceImpl method unschedule.

public void unschedule(long taskId, DeadlineType type) {
    Task task = persistenceContext.findTask(taskId);
    String deploymentId = task.getTaskData().getDeploymentId();
    Deadlines deadlines = ((InternalTask) task).getDeadlines();
    TimerService timerService = TimerServiceRegistry.getInstance().get(deploymentId + TimerServiceRegistry.TIMER_SERVICE_SUFFIX);
    if (timerService != null && timerService instanceof GlobalTimerService) {
        if (type == DeadlineType.START) {
            List<Deadline> startDeadlines = deadlines.getStartDeadlines();
            List<DeadlineSummary> resultList = (List<DeadlineSummary>) persistenceContext.queryWithParametersInTransaction("UnescalatedStartDeadlinesByTaskId", persistenceContext.addParametersToMap("taskId", taskId), ClassUtil.<List<DeadlineSummary>>castClass(List.class));
            for (DeadlineSummary summary : resultList) {
                TaskDeadlineJob deadlineJob = new TaskDeadlineJob(summary.getTaskId(), summary.getDeadlineId(), DeadlineType.START, deploymentId, task.getTaskData().getProcessInstanceId());
                logger.debug("unscheduling timer job for deadline {} {} and task {}  using timer service {}", deadlineJob.getId(), summary.getDeadlineId(), taskId, timerService);
                JobHandle jobHandle = jobHandles.remove(deadlineJob.getId());
                if (jobHandle == null) {
                    jobHandle = ((GlobalTimerService) timerService).buildJobHandleForContext(new TaskDeadlineJobContext(deadlineJob.getId(), task.getTaskData().getProcessInstanceId(), deploymentId));
                }
                timerService.removeJob(jobHandle);
                // mark the deadlines so they won't be rescheduled again
                for (Deadline deadline : startDeadlines) {
                    if (deadline.getId() == summary.getDeadlineId()) {
                        deadline.setEscalated(true);
                    }
                }
            }
        } else if (type == DeadlineType.END) {
            List<Deadline> endDeadlines = deadlines.getStartDeadlines();
            List<DeadlineSummary> resultList = (List<DeadlineSummary>) persistenceContext.queryWithParametersInTransaction("UnescalatedEndDeadlinesByTaskId", persistenceContext.addParametersToMap("taskId", taskId), ClassUtil.<List<DeadlineSummary>>castClass(List.class));
            for (DeadlineSummary summary : resultList) {
                TaskDeadlineJob deadlineJob = new TaskDeadlineJob(summary.getTaskId(), summary.getDeadlineId(), DeadlineType.END, deploymentId, task.getTaskData().getProcessInstanceId());
                logger.debug("unscheduling timer job for deadline {} and task {}  using timer service {}", deadlineJob.getId(), taskId, timerService);
                JobHandle jobHandle = jobHandles.remove(deadlineJob.getId());
                if (jobHandle == null) {
                    jobHandle = ((GlobalTimerService) timerService).buildJobHandleForContext(new TaskDeadlineJobContext(deadlineJob.getId(), task.getTaskData().getProcessInstanceId(), deploymentId));
                }
                timerService.removeJob(jobHandle);
                // mark the deadlines so they won't be rescheduled again
                for (Deadline deadline : endDeadlines) {
                    if (deadline.getId() == summary.getDeadlineId()) {
                        deadline.setEscalated(true);
                    }
                }
            }
        }
    } else {
        List<ScheduledFuture<ScheduledTaskDeadline>> knownFutures = null;
        if (type == DeadlineType.START) {
            knownFutures = startScheduledTaskDeadlines.get(taskId);
        } else if (type == DeadlineType.END) {
            knownFutures = endScheduledTaskDeadlines.get(taskId);
        }
        if (knownFutures == null) {
            return;
        }
        Iterator<ScheduledFuture<ScheduledTaskDeadline>> it = knownFutures.iterator();
        while (it.hasNext()) {
            ScheduledFuture<ScheduledTaskDeadline> scheduled = it.next();
            try {
                if (!scheduled.isDone() && !scheduled.isCancelled()) {
                    scheduled.cancel(true);
                }
            } catch (Exception e) {
                logger.error("Error while cancelling scheduled deadline task for Task with id {} -> {}", taskId, e);
            }
        }
    }
}
Also used : Task(org.kie.api.task.model.Task) InternalTask(org.kie.internal.task.api.model.InternalTask) InternalTask(org.kie.internal.task.api.model.InternalTask) DeadlineSummary(org.kie.internal.task.api.model.DeadlineSummary) Deadline(org.kie.internal.task.api.model.Deadline) GlobalTimerService(org.jbpm.process.core.timer.impl.GlobalTimerService) TimerService(org.drools.core.time.TimerService) ScheduledFuture(java.util.concurrent.ScheduledFuture) JobHandle(org.drools.core.time.JobHandle) Deadlines(org.kie.internal.task.api.model.Deadlines) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) GlobalTimerService(org.jbpm.process.core.timer.impl.GlobalTimerService)

Example 10 with GlobalTimerService

use of org.jbpm.process.core.timer.impl.GlobalTimerService in project jbpm by kiegroup.

the class GlobalQuartzDBTimerServiceTest method testContinueGlobalTestService.

/**
 * Test that illustrates that jobs are persisted and survives server restart
 * and as soon as GlobalTimerService is active jobs are fired
 * NOTE: this test is disabled by default as it requires real db (not in memory)
 * and test to be executed separately each with new jvm process
 */
@Test
@Ignore
public void testContinueGlobalTestService() throws Exception {
    RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get().newDefaultBuilder().entityManagerFactory(emf).addAsset(ResourceFactory.newClassPathResource("org/jbpm/test/functional/timer/IntermediateCatchEventTimerCycle2.bpmn2"), ResourceType.BPMN2).addConfiguration("drools.timerService", "org.jbpm.process.core.timer.impl.RegisteredTimerServiceDelegate").get();
    RuntimeManager manger = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
    // build GlobalTimerService instance
    TimerService globalTs = new GlobalTimerService(manger, globalScheduler);
    // and register it in the registry under 'default' key
    TimerServiceRegistry.getInstance().registerTimerService("default", globalTs);
    // prepare listener to assert results
    final List<Long> timerExporations = new ArrayList<Long>();
    ProcessEventListener listener = new DefaultProcessEventListener() {

        @Override
        public void afterNodeLeft(ProcessNodeLeftEvent event) {
            if (event.getNodeInstance().getNodeName().equals("timer")) {
                timerExporations.add(event.getProcessInstance().getId());
            }
        }
    };
    Thread.sleep(5000);
}
Also used : RuntimeEnvironment(org.kie.api.runtime.manager.RuntimeEnvironment) ProcessEventListener(org.kie.api.event.process.ProcessEventListener) DefaultProcessEventListener(org.kie.api.event.process.DefaultProcessEventListener) NodeLeftCountDownProcessEventListener(org.jbpm.test.listener.NodeLeftCountDownProcessEventListener) RuntimeManager(org.kie.api.runtime.manager.RuntimeManager) AbstractRuntimeManager(org.jbpm.runtime.manager.impl.AbstractRuntimeManager) ArrayList(java.util.ArrayList) DefaultProcessEventListener(org.kie.api.event.process.DefaultProcessEventListener) ProcessNodeLeftEvent(org.kie.api.event.process.ProcessNodeLeftEvent) GlobalTimerService(org.jbpm.process.core.timer.impl.GlobalTimerService) TimerService(org.drools.core.time.TimerService) GlobalTimerService(org.jbpm.process.core.timer.impl.GlobalTimerService) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

GlobalTimerService (org.jbpm.process.core.timer.impl.GlobalTimerService)12 TimerService (org.drools.core.time.TimerService)11 ArrayList (java.util.ArrayList)3 JobHandle (org.drools.core.time.JobHandle)3 Test (org.junit.Test)3 Task (org.kie.api.task.model.Task)3 Disposable (org.kie.internal.runtime.manager.Disposable)3 InternalTask (org.kie.internal.task.api.model.InternalTask)3 List (java.util.List)2 ScheduledFuture (java.util.concurrent.ScheduledFuture)2 GlobalSchedulerService (org.jbpm.process.core.timer.GlobalSchedulerService)2 SchedulerProvider (org.jbpm.runtime.manager.api.SchedulerProvider)2 AbstractRuntimeManager (org.jbpm.runtime.manager.impl.AbstractRuntimeManager)2 InMemoryMapper (org.jbpm.runtime.manager.impl.mapper.InMemoryMapper)2 NodeLeftCountDownProcessEventListener (org.jbpm.test.listener.NodeLeftCountDownProcessEventListener)2 Ignore (org.junit.Ignore)2 DefaultProcessEventListener (org.kie.api.event.process.DefaultProcessEventListener)2 ProcessEventListener (org.kie.api.event.process.ProcessEventListener)2 ProcessNodeLeftEvent (org.kie.api.event.process.ProcessNodeLeftEvent)2 RuntimeEngine (org.kie.api.runtime.manager.RuntimeEngine)2