Search in sources :

Example 1 with TimerSchedulerTask

use of org.openmrs.scheduler.timer.TimerSchedulerTask in project openmrs-core by openmrs.

the class Daemon method executeScheduledTask.

/**
 * Executes the given task in a new thread that is authenticated as the daemon user. <br>
 * <br>
 * This can only be called from {@link TimerSchedulerTask} during actual task execution
 *
 * @param task the task to run
 * @should not be called from other methods other than TimerSchedulerTask
 * @should not throw error if called from a TimerSchedulerTask class
 */
public static void executeScheduledTask(final Task task) throws Exception {
    // quick check to make sure we're only being called by ourselves
    Class<?> callerClass = new OpenmrsSecurityManager().getCallerClass(0);
    if (!TimerSchedulerTask.class.isAssignableFrom(callerClass)) {
        throw new APIException("Scheduler.timer.task.only", new Object[] { callerClass.getName() });
    }
    // now create a new thread and execute that task in it
    DaemonThread executeTaskThread = new DaemonThread() {

        @Override
        public void run() {
            isDaemonThread.set(true);
            try {
                Context.openSession();
                TimerSchedulerTask.execute(task);
            } catch (Exception e) {
                exceptionThrown = e;
            } finally {
                Context.closeSession();
            }
        }
    };
    executeTaskThread.start();
    // wait for the "executeTaskThread" thread to finish
    try {
        executeTaskThread.join();
    } catch (InterruptedException e) {
    // ignore
    }
    if (executeTaskThread.exceptionThrown != null) {
        throw executeTaskThread.exceptionThrown;
    }
}
Also used : TimerSchedulerTask(org.openmrs.scheduler.timer.TimerSchedulerTask) APIException(org.openmrs.api.APIException) OpenmrsSecurityManager(org.openmrs.util.OpenmrsSecurityManager) APIException(org.openmrs.api.APIException) ModuleException(org.openmrs.module.ModuleException) APIAuthenticationException(org.openmrs.api.APIAuthenticationException)

Aggregations

APIAuthenticationException (org.openmrs.api.APIAuthenticationException)1 APIException (org.openmrs.api.APIException)1 ModuleException (org.openmrs.module.ModuleException)1 TimerSchedulerTask (org.openmrs.scheduler.timer.TimerSchedulerTask)1 OpenmrsSecurityManager (org.openmrs.util.OpenmrsSecurityManager)1