Run this task now

@param bool $tryLockJob
@param bool $forceRun
@return Aoe_Scheduler_Model_Schedule
19430
public function runNow($tryLockJob = true, $forceRun = false)
    {
        // Check the user running the cron is the one defined in config
        if (!$this->checkRunningAsCorrectUser()) {
            $this->setStatus(self::STATUS_SKIP_WRONGUSER)->save();
            return $this;
        }

        // if this schedule doesn't exist yet, create it
        if (!$this->getCreatedAt()) {
            $this->schedule();
        }

        if (!$forceRun) {
            // lock job (see below) prevents the exact same schedule from being executed from more than one process (or server)
            // the following check will prevent multiple schedules of the same type to be run in parallel
            $processManager = Mage::getModel('aoe_scheduler/processManager'); /* @var $processManager Aoe_Scheduler_Model_ProcessManager */
            if ($processManager->isJobCodeRunning($this->getJobCode(), $this->getId())) {
                $this->getResource()->trySetJobStatusAtomic(
                    $this->getId(),
                    Aoe_Scheduler_Model_Schedule::STATUS_SKIP_OTHERJOBRUNNING,
                    Aoe_Scheduler_Model_Schedule::STATUS_PENDING
                );
                $this->log(sprintf('Job "%s" (id: %s) will not be executed because there is already another process with the same job code running. Skipping.', $this->getJobCode(), $this->getId()));
                return $this;
            }
        }

        // lock job requires the record to be saved and having status Aoe_Scheduler_Model_Schedule::STATUS_PENDING
        // workaround could be to do this: $this->setStatus(Aoe_Scheduler_Model_Schedule::STATUS_PENDING)->save();
        $this->jobWasLocked = false;
        if ($tryLockJob && !$this->tryLockJob()) {
            // another cron started this job intermittently, so skip it
            $this->jobWasLocked = true;
            $this->log(sprintf('Job "%s" (id: %s) is locked. Skipping.', $this->getJobCode(), $this->getId()));
            return $this;
        }

        try {
            // Track the last user to run a job
            $this->setLastRunUser();

            $job = $this->getJob();

            if (!$job) {
                Mage::throwException(sprintf("Could not create job with jobCode '%s'", $this->getJobCode()));
            }

            $startTime = time();
            $this
                ->setExecutedAt(strftime('%Y-%m-%d %H:%M:%S', $startTime))
                ->setLastSeen(strftime('%Y-%m-%d %H:%M:%S', $startTime))
                ->setStatus(Aoe_Scheduler_Model_Schedule::STATUS_RUNNING)
                ->setHost(gethostname())
                ->setPid(getmypid())
                ->save();

            Aoe_Scheduler_Helper_GracefulDead::configure();

            Mage::register('currently_running_schedule', $this);

            Mage::dispatchEvent('cron_' . $this->getJobCode() . '_before', array('schedule' => $this));
            Mage::dispatchEvent('cron_before', array('schedule' => $this));

            Mage::unregister('current_cron_task');
            Mage::register('current_cron_task', $this);

            $this->log('Start: ' . $this->getJobCode());

            $this->_startBufferToMessages();
            $this->jobErrorContext();

            $callback = $job->getCallback();

            try {
                // this is where the magic happens
                $messages = call_user_func_array($callback, array($this));

                $this->restoreErrorContext();
                $this->_stopBufferToMessages();
            } catch (Exception $e) {
                $this->restoreErrorContext();
                $this->_stopBufferToMessages();
                throw $e;
            }

            $this->log('Stop: ' . $this->getJobCode());

            if (!empty($messages)) {
                if (is_object($messages)) {
                    $messages = get_class($messages);
                } elseif (!is_scalar($messages)) {
                    $messages = var_export($messages, 1);
                }
                $this->addMessages(PHP_EOL . '---RETURN_VALUE---' . PHP_EOL . $messages);
            }

            // schedules can report an error state by returning a string that starts with "ERROR:", "NOTHING", or "REPEAT"
            // or they can set set the status directly to the schedule object that's passed as a parameter
            if ((is_string($messages) && strtoupper(substr($messages, 0, 6)) == 'ERROR:') || $this->getStatus() === Aoe_Scheduler_Model_Schedule::STATUS_ERROR) {
                $this->setStatus(Aoe_Scheduler_Model_Schedule::STATUS_ERROR);
                Mage::helper('aoe_scheduler')->sendErrorMail($this, $messages);
                Mage::dispatchEvent('cron_' . $this->getJobCode() . '_after_error', array('schedule' => $this));
                Mage::dispatchEvent('cron_after_error', array('schedule' => $this));
            } elseif ((is_string($messages) && strtoupper(substr($messages, 0, 7)) == 'NOTHING') || $this->getStatus() === Aoe_Scheduler_Model_Schedule::STATUS_DIDNTDOANYTHING) {
                $this->setStatus(Aoe_Scheduler_Model_Schedule::STATUS_DIDNTDOANYTHING);
                Mage::dispatchEvent('cron_' . $this->getJobCode() . '_after_nothing', array('schedule' => $this));
                Mage::dispatchEvent('cron_after_nothing', array('schedule' => $this));
            } elseif ((is_string($messages) && strtoupper(substr($messages, 0, 6)) == 'REPEAT') || $this->getStatus() === Aoe_Scheduler_Model_Schedule::STATUS_REPEAT) {
                $this->setStatus(Aoe_Scheduler_Model_Schedule::STATUS_REPEAT);
                Mage::dispatchEvent('cron_' . $this->getJobCode() . '_after_repeat', array('schedule' => $this));
                Mage::dispatchEvent('cron_after_repeat', array('schedule' => $this));
            } else {
                $this->setStatus(Aoe_Scheduler_Model_Schedule::STATUS_SUCCESS);
                Mage::dispatchEvent('cron_' . $this->getJobCode() . '_after_success', array('schedule' => $this));
                Mage::dispatchEvent('cron_after_success', array('schedule' => $this));

                $this->scheduleOnSuccessDependencies();
            }

        } catch (Exception $e) {
            $this->setStatus(Aoe_Scheduler_Model_Schedule::STATUS_ERROR);
            $this->addMessages(PHP_EOL . '---EXCEPTION---' . PHP_EOL . $e->__toString());
            Mage::dispatchEvent('cron_' . $this->getJobCode() . '_exception', array('schedule' => $this, 'exception' => $e));
            Mage::dispatchEvent('cron_exception', array('schedule' => $this, 'exception' => $e));
            Mage::helper('aoe_scheduler')->sendErrorMail($this, $e->__toString());
        }

        $this->setFinishedAt(strftime('%Y-%m-%d %H:%M:%S', time()));
        $this->setMemoryUsage(memory_get_peak_usage(true) / pow(1024, 2));  // convert bytes to megabytes
        Mage::dispatchEvent('cron_' . $this->getJobCode() . '_after', array('schedule' => $this));
        Mage::dispatchEvent('cron_after', array('schedule' => $this));

        $this->save();
        Mage::unregister('currently_running_schedule');

        return $this;
    }
430689
private boolean runQueuedTask(boolean hasPermit) {
        if (!hasPermit && beginRequest(paused) == RunResult.REJECTED) {
            return false;
        }
        QueuedTask task = null;
        if (!paused) {
            task = taskQueue.poll();
        } else {
            //the container is suspended, but we still need to run any force queued tasks
            task = findForcedTask();
        }
        if (task != null) {
            if(!task.runRequest()) {
                decrementRequestCount();
            }
            return true;
        } else {
            decrementRequestCount();
            return false;
        }
    }
1183699
public function lock($taskCallable = null, $afterLockCallable = null)
    {
        if($this->isLocked())
        {
            return false;
        }
        if(!$this->__lock())
        {
            return false;
        }
        if(null === $taskCallable)
        {
            return true;
        }
        else
        {
            try {
                if(null !== $afterLockCallable && true === $afterLockCallable())
                {
                    return true;
                }
                $taskCallable();
                return true;
            } catch (\Throwable $th) {
                throw $th;
            } finally {
                $this->unlock();
            }
        }
    }
1257328
void invokeAndWait(final Runnable r) {
        final CountDownLatch latch = new CountDownLatch(1);
        queue.postRunnable(() -> {
            try {
                r.run();
            } finally {
                latch.countDown();
            }
        });
        try {
            latch.await();
        } catch (InterruptedException e) { }
    }
62854
private static OptimisticLockingException callFailedJobListenerWithRetries(CommandExecutor commandExecutor, FailedJobListener failedJobListener) {
    try {
      commandExecutor.execute(failedJobListener);
      return null;
    } catch (OptimisticLockingException ex) {
      failedJobListener.incrementCountRetries();
      if (failedJobListener.getRetriesLeft() > 0) {
        return callFailedJobListenerWithRetries(commandExecutor, failedJobListener);
      }
      return ex;
    }
  }
703197
private void runJob(Job jobToRun) {
		long startExecutionTime = timeProvider.currentTime();
		long timeBeforeNextExecution = jobToRun.nextExecutionTimeInMillis() - startExecutionTime;
		if(timeBeforeNextExecution < 0) {
			logger.debug("Job '{}' execution is {}ms late", jobToRun.name(), -timeBeforeNextExecution);
		}
		jobToRun.status(JobStatus.RUNNING);
		jobToRun.lastExecutionStartedTimeInMillis(startExecutionTime);
		jobToRun.threadRunningJob(Thread.currentThread());

		try {
			jobToRun.runnable().run();
		} catch(Throwable t) {
			logger.error("Error during job '{}' execution", jobToRun.name(), t);
		}
		jobToRun.executionsCount(jobToRun.executionsCount() + 1);
		jobToRun.lastExecutionEndedTimeInMillis(timeProvider.currentTime());
		jobToRun.threadRunningJob(null);

		if(logger.isDebugEnabled()) {
			logger.debug(
				"Job '{}' executed in {}ms", jobToRun.name(),
				timeProvider.currentTime() - startExecutionTime
			);
		}

		if(shuttingDown) {
			return;
		}
		synchronized (this) {
			scheduleNextExecution(jobToRun);
		}
	}
555820
public function acquireLock() {
        $this->log("[JOB] attempting to acquire lock for job::{$this->job_id} on {$this->worker_name}", self::INFO);

        $lock = $this->runUpdate("
            UPDATE " . self::$jobsTable . "
            SET    locked_at = NOW(), locked_by = ?
            WHERE  id = ? AND (locked_at IS NULL OR locked_by = ?) AND failed_at IS NULL
        ", array($this->worker_name, $this->job_id, $this->worker_name));

        if (!$lock) {
            $this->log("[JOB] failed to acquire lock for job::{$this->job_id}", self::INFO);
            return false;
        }

        return true;
    }
435787
def checkForDeadlocks(self):
        
        totalRunningJobs = len(self.batchSystem.getRunningBatchJobIDs())
        totalServicesIssued = self.serviceJobsIssued + self.preemptableServiceJobsIssued
        # If there are no updated jobs and at least some jobs running
        if totalServicesIssued >= totalRunningJobs and totalRunningJobs > 0:
            serviceJobs = [x for x in list(self.jobBatchSystemIDToIssuedJob.keys()) if isinstance(self.jobBatchSystemIDToIssuedJob[x], ServiceJobNode)]
            runningServiceJobs = set([x for x in serviceJobs if self.serviceManager.isRunning(self.jobBatchSystemIDToIssuedJob[x])])
            assert len(runningServiceJobs) <= totalRunningJobs

            # If all the running jobs are active services then we have a potential deadlock
            if len(runningServiceJobs) == totalRunningJobs:
                # We wait self.config.deadlockWait seconds before declaring the system deadlocked
                if self.potentialDeadlockedJobs != runningServiceJobs:
                    self.potentialDeadlockedJobs = runningServiceJobs
                    self.potentialDeadlockTime = time.time()
                elif time.time() - self.potentialDeadlockTime >= self.config.deadlockWait:
                    raise DeadlockException("The system is service deadlocked - all %d running jobs are active services" % totalRunningJobs)
            else:
                # We have observed non-service jobs running, so reset the potential deadlock
                self.potentialDeadlockedJobs = set()
                self.potentialDeadlockTime = 0
        else:
            # We have observed non-service jobs running, so reset the potential deadlock
            self.potentialDeadlockedJobs = set()
            self.potentialDeadlockTime = 0
904467
@Override
    public void run() {
        final boolean trace = TraceComponent.isAnyTracingEnabled();
        if (trace && tc.isEntryEnabled())
            Tr.entry(this, tc, "run[" + taskId + ']', persistentExecutor);

        Config config = persistentExecutor.configRef.get();
        if (persistentExecutor.deactivated || !config.enableTaskExecution) {
            if (trace && tc.isEntryEnabled())
                Tr.exit(this, tc, "run[" + taskId + ']', persistentExecutor.deactivated ? "deactivated" : ("enableTaskExecution? " + config.enableTaskExecution));
            return;
        }

        // Work around for when the scheduled executor fires too early
        long execTime = new Date().getTime();
        if (execTime < expectedExecTime) {
            long delay = expectedExecTime - execTime;
            persistentExecutor.scheduledExecutor.schedule(this, delay, TimeUnit.MILLISECONDS);
            if (trace && tc.isEntryEnabled())
                Tr.exit(this, tc, "run[" + taskId + ']', "attempted to run " + delay + " ms too early. Rescheduled.");
            return;
        }

        // If a Configuration update is in progress, then we will defer the execution of this Task until after.
        if (persistentExecutor.deferExecutionForConfigUpdate(this) == true) {
            if (trace && tc.isEntryEnabled())
                Tr.exit(this, tc, "run[" + taskId + ']', "attempted to run during a configuration update.");
            return;
        }

        String taskName = null;
        String taskIdForPropTable = null;
        TaskLocker ejbSingletonLockCollaborator = null;
        String ownerForDeferredTask = null;
        ClassLoader loader = null;
        Throwable failure = null;
        Short prevFailureCount = null, nextFailureCount = null;
        Long nextExecTime = null;
        TaskStore taskStore = persistentExecutor.taskStore;
        ApplicationTracker appTracker = persistentExecutor.appTrackerRef.getServiceWithException();
        TransactionManager tranMgr = persistentExecutor.tranMgrRef.getServiceWithException();
        taskIdsOfRunningTasks.set(taskId);
        try {
            int timeout = txTimeout == 0 && (binaryFlags & TaskRecord.Flags.SUSPEND_TRAN_OF_EXECUTOR_THREAD.bit) != 0 ? DEFAULT_TIMEOUT_FOR_SUSPENDED_TRAN : txTimeout;
            tranMgr.setTransactionTimeout(timeout);

            TaskRecord ejbSingletonRecord = null;
            if ((binaryFlags & TaskRecord.Flags.EJB_SINGLETON.bit) != 0 && (binaryFlags & TaskRecord.Flags.SUSPEND_TRAN_OF_EXECUTOR_THREAD.bit) == 0) {
                tranMgr.begin();
                ejbSingletonRecord = taskStore.getTrigger(taskId);
                tranMgr.commit();
            }

            tranMgr.begin();
            TaskRecord taskRecord;

            // Execution property TRANSACTION=SUSPEND indicates the task should not run in the persistent executor transaction.
            // Lock an entry in a different table to prevent concurrent execution, and run with that transaction suspended.
            if ((binaryFlags & TaskRecord.Flags.SUSPEND_TRAN_OF_EXECUTOR_THREAD.bit) != 0) {
                if (!taskStore.createProperty(taskIdForPropTable = "{" + taskId + "}", " "))
                    throw new IllegalStateException(taskIdForPropTable); // Internal error if this path is ever reached
                Transaction suspendedTran = tranMgr.suspend();
                try {
                    // We still need the task information, but get it in a new transaction that we can commit right away.
                    Throwable failed = null;
                    tranMgr.begin();
                    try {
                        taskRecord = taskStore.find(taskId,
                                                    persistentExecutor.getPartitionId(),
                                                    new Date().getTime(),
                                                    false);
                    } catch (Throwable x) {
                        throw failed = x;
                    } finally {
                        if (failed == null)
                            tranMgr.commit();
                        else
                            tranMgr.rollback();
                    }
                } finally {
                    tranMgr.resume(suspendedTran); // will be suspended again by application of transaction context
                }
            } else {
                if (ejbSingletonRecord != null) {
                    String owner = ejbSingletonRecord.getIdentifierOfOwner();
                    if (!appTracker.isStarted(owner)) {
                        ownerForDeferredTask = owner;
                        if (trace && tc.isEntryEnabled())
                            Tr.exit(this, tc, "run[" + taskId + ']', "unavailable - deferred");
                        return; // Ignore, we are deferring the task because the application or module is unavailable
                    }

                    byte[] bytes = ejbSingletonRecord.getTrigger();
                    ejbSingletonLockCollaborator = (TaskLocker) persistentExecutor.deserialize(bytes, priv.getSystemClassLoader());
                    if (trace && tc.isDebugEnabled())
                        Tr.debug(this, tc, "notify EJB container to lock singleton");
                    ejbSingletonLockCollaborator.lock();
                }

                taskRecord = taskStore.find(taskId,
                                            persistentExecutor.getPartitionId(),
                                            new Date().getTime(),
                                            true);
            }

            if (taskRecord == null || (taskRecord.getState() & TaskState.ENDED.bit) != 0) {
                if (trace && tc.isEntryEnabled())
                    Tr.exit(this, tc, "run[" + taskId + ']', "not appropriate to run task at this time");
                return; // Ignore, because the task was canceled or someone else already ran it
            }

            taskName = taskRecord.getName();
            prevFailureCount = taskRecord.getConsecutiveFailureCount();

            String classLoaderIdentifier = taskRecord.getIdentifierOfClassLoader();
            if (trace && tc.isDebugEnabled())
                Tr.debug(this, tc, "classloader identifier", classLoaderIdentifier);
            loader = ejbSingletonRecord == null ? persistentExecutor.classloaderIdSvc.getClassLoader(classLoaderIdentifier) : priv.getSystemClassLoader();
            if (trace && tc.isDebugEnabled())
                Tr.debug(this, tc, "classloader", loader);

            String owner = taskRecord.getIdentifierOfOwner();
            if (loader == null || !appTracker.isStarted(owner)) {
                ownerForDeferredTask = owner;
                if (trace && tc.isEntryEnabled())
                    Tr.exit(this, tc, "run[" + taskId + ']', "unavailable - deferred");
                return; // Ignore, we are deferring the task because the application or module is unavailable
            }

            TaskInfo info = (TaskInfo) persistentExecutor.deserialize(taskRecord.getTaskInformation(), null);

            byte[] triggerBytes = taskRecord.getTrigger();
            Trigger trigger = triggerBytes == null ? null : ejbSingletonRecord != null
                                                            && Arrays.equals(triggerBytes,
                                                                             ejbSingletonRecord.getTrigger()) ? ejbSingletonLockCollaborator : (Trigger) persistentExecutor.deserialize(triggerBytes,
                                                                                                                                                                                        loader);
            if (trigger == null) {
                String triggerClassName = info.getClassNameForNonSerializableTrigger();
                if (triggerClassName != null)
                    trigger = (Trigger) loader.loadClass(triggerClassName).newInstance();
            }

            byte[] taskBytes = taskRecord.getTask();
            Object task = taskBytes == null ? null : persistentExecutor.deserialize(taskBytes, loader);
            if (task == null) {
                String taskClassName = info.getClassNameForNonSerializableTask();
                if (taskClassName == null)
                    task = trigger; // optimization to share single instance for task and trigger
                else
                    task = loader.loadClass(taskClassName).newInstance();
            }

            byte[] resultBytes = taskRecord.getResult();

            boolean skipped = false;
            Throwable skippedX = null;
            LastExecution lastExecution = null;
            long startTime = 0, stopTime = 0;
            Object result = null;

            Map<String, String> execProps = persistentExecutor.getExecutionProperties(task);
            ThreadContextDescriptor threadContext = info.deserializeThreadContext(execProps);
            ArrayList<ThreadContext> contextAppliedToThread = threadContext == null ? null : threadContext.taskStarting();
            try {
                if (trigger != null) {
                    Long prevScheduledStart = taskRecord.getPreviousScheduledStartTime();
                    if (prevScheduledStart != null)
                        lastExecution = new LastExecutionImpl(persistentExecutor, taskId, taskName, resultBytes, taskRecord.getPreviousStopTime(), taskRecord.getPreviousStartTime(), prevScheduledStart, loader);
                    try {
                        skipped = trigger.skipRun(lastExecution, new Date(taskRecord.getNextExecutionTime()));
                    } catch (RuntimeException x) {
                        skipped = true;
                        skippedX = x;
                    }
                }

                if (skipped) {
                    if (trace && tc.isDebugEnabled())
                        Tr.debug(this, tc, "skipping task", skippedX);
                    Date nextExecDate = trigger.getNextRunTime(lastExecution, new Date(taskRecord.getOriginalSubmitTime()));
                    nextExecTime = nextExecDate == null ? null : nextExecDate.getTime();
                } else {
                    // Fixed result for one-shot runnable
                    if (!info.isSubmittedAsCallable() && info.getInterval() == -1 && trigger == null && resultBytes != null)
                        result = persistentExecutor.deserialize(resultBytes, loader);

                    if (trace && tc.isDebugEnabled())
                        Tr.debug(this, tc, "task about to start " + task);

                    startTime = new Date().getTime();
                    try {
                        if (info.isSubmittedAsCallable())
                            result = ((Callable<?>) task).call();
                        else
                            ((Runnable) task).run();

                        if (trace && tc.isDebugEnabled())
                            Tr.debug(this, tc, "task result " + result);
                        nextFailureCount = (short) 0;
                    } catch (Throwable x) {
                        if (trace && tc.isDebugEnabled())
                            Tr.debug(this, tc, "task failed", x);
                        failure = x;
                        nextFailureCount = (short) ((prevFailureCount < Short.MAX_VALUE) ? (prevFailureCount + 1) : Short.MAX_VALUE);
                        // If we will retry, immediately roll back, then can update persistent store with failure count
                        config = persistentExecutor.configRef.get();
                        if (config.retryLimit == -1 || nextFailureCount <= config.retryLimit)
                            throw failure;
                    } finally {
                        stopTime = new Date().getTime();
                    }

                    // Compute next execution time if the task did not fail.
                    if (failure == null) {
                        long interval = info.getInterval();
                        if (interval == -1) {
                            if (trigger == null) {
                                nextExecTime = null; // one-shot task
                            } else {
                                lastExecution = new LastExecutionImpl(persistentExecutor, taskId, taskName, result, stopTime, startTime, taskRecord.getNextExecutionTime());
                                Date nextExecDate = trigger.getNextRunTime(lastExecution, new Date(taskRecord.getOriginalSubmitTime()));
                                nextExecTime = nextExecDate == null ? null : nextExecDate.getTime();
                            }
                        } else if (info.isFixedRate()) {
                            long originalScheduledStartTime = taskRecord.getOriginalSubmitTime() + info.getInitialDelay();
                            long elapsed = stopTime - originalScheduledStartTime;
                            nextExecTime = (elapsed / interval + 1) * interval + originalScheduledStartTime;
                        } else
                            nextExecTime = stopTime + interval; // fixed-delay
                    }
                }
            } finally {
                if (contextAppliedToThread != null)
                    threadContext.taskStopping(contextAppliedToThread);
            }

            short autoPurgeBit = failure == null ? TaskRecord.Flags.AUTO_PURGE_ON_SUCCESS.bit : TaskRecord.Flags.AUTO_PURGE_ALWAYS.bit;

            if ((nextExecTime == null || !skipped && nextFailureCount > 0) && (binaryFlags & autoPurgeBit) != 0) {
                // Autopurge the completed task if it hasn't already been ended (removal/cancellation by self or other)
                taskStore.remove(taskId, null, false);
            } else {
                // Update state
                TaskRecord updates = new TaskRecord(false);
                if (nextExecTime != null)
                    updates.setNextExecutionTime(nextExecTime);
                short state = nextExecTime == null ? (short) (TaskState.ENDED.bit | TaskState.SUCCESSFUL.bit) : TaskState.SCHEDULED.bit;
                if (skipped) {
                    state |= TaskState.SKIPPED.bit;
                    if (skippedX != null) {
                        state |= TaskState.SKIPRUN_FAILED.bit;
                        byte[] previousResultBytes = persistentExecutor.serialize(lastExecution == null ? null : lastExecution.getResult());
                        updates.setResult(persistentExecutor.serialize(new TaskSkipped(previousResultBytes, skippedX, loader, persistentExecutor)));
                    }
                } else {
                    updates.setConsecutiveFailureCount(nextFailureCount);
                    updates.setPreviousScheduledStartTime(taskRecord.getNextExecutionTime());
                    updates.setPreviousStartTime(startTime);
                    updates.setPreviousStopTime(stopTime);
                    if (failure == null) {
                        // Only update result blob if it changed
                        byte[] updatedResultBytes = result == null ? null : serializeResult(result, loader);
                        if (updatedResultBytes == null || !Arrays.equals(resultBytes, updatedResultBytes))
                            updates.setResult(updatedResultBytes);
                    } else {
                        updates.setResult(persistentExecutor.serialize(new TaskFailure(failure, loader, persistentExecutor, TaskFailure.FAILURE_LIMIT_REACHED, Short.toString(nextFailureCount))));
                        state = (short) (TaskState.ENDED.bit | TaskState.FAILURE_LIMIT_REACHED.bit);
                    }
                }
                updates.setState(state);
                // Only update blobs if they have changed
                if (taskBytes != null) {
                    byte[] updatedTaskBytes = persistentExecutor.serialize(task);
                    if (!Arrays.equals(taskBytes, updatedTaskBytes))
                        updates.setTask(updatedTaskBytes);
                }
                if (triggerBytes != null) {
                    byte[] updatedTriggerBytes = persistentExecutor.serialize(trigger);
                    if (!Arrays.equals(triggerBytes, updatedTriggerBytes))
                        updates.setTrigger(updatedTriggerBytes);
                }
                TaskRecord expected = new TaskRecord(false);
                expected.setId(taskId);
                expected.setVersion(taskRecord.getVersion());
                boolean updatesPersisted = taskStore.persist(updates, expected);

                if (!updatesPersisted) {
                    // Optimistic update unsuccessful. Need to take into account changes made by the task to itself.
                    TaskRecord taskRecordRefresh = taskStore.findById(taskId, null, false);
                    if (taskRecordRefresh != null) {
                        short refreshedState = taskRecordRefresh.getState();
                        if ((refreshedState & TaskState.CANCELED.bit) != 0
                            && (binaryFlags & TaskRecord.Flags.SUSPEND_TRAN_OF_EXECUTOR_THREAD.bit) == 0) {
                            // task canceled itself, combine the canceled state with other updates
                            updates.setState(state = refreshedState);
                            expected.setVersion(taskRecordRefresh.getVersion());
                            taskStore.persist(updates, expected);
                        } else if ((refreshedState & TaskState.SUSPENDED.bit) != 0) {
                            // task suspended itself, merge the suspended state with new state and combine with other updates
                            state |= TaskState.SUSPENDED.bit;
                            state &= ~TaskState.SCHEDULED.bit;
                            expected.setVersion(taskRecordRefresh.getVersion());
                            taskStore.persist(updates, expected);
                        }
                    } // else the task removed itself
                }
            }
        } catch (Throwable x) {
            if (trace && tc.isDebugEnabled())
                Tr.debug(this, tc, "marking transaction to roll back in response to error", x);
            try {
                tranMgr.setRollbackOnly();
            } catch (Throwable t) {
            }
            if (failure == null)
                failure = x;
        } finally {
            if (ejbSingletonLockCollaborator != null)
                ejbSingletonLockCollaborator.unlock();

            taskIdsOfRunningTasks.remove();

            try {
                tranMgr.setTransactionTimeout(0); // clear the value so we don't impact subsequent transactions on this thread

                if (tranMgr.getStatus() == Status.STATUS_MARKED_ROLLBACK) {
                    if (trace && tc.isEventEnabled())
                        Tr.event(this, tc, "rolling back task execution attempt");
                    if (nextFailureCount == null || nextFailureCount == 0)
                        nextFailureCount = (short) (prevFailureCount == null ? 1 : prevFailureCount < Short.MAX_VALUE ? (prevFailureCount + 1) : Short.MAX_VALUE);
                    tranMgr.rollback();
                    if (config == null)
                        config = persistentExecutor.configRef.get();
                    processRetryableTaskFailure(failure, loader, nextFailureCount, config, taskName);
                } else {
                    if (taskIdForPropTable != null)
                        taskStore.removeProperty(taskIdForPropTable);

                    tranMgr.commit();

                    // Immediately reschedule tasks that should run in the near future if the transaction commits
                    config = persistentExecutor.configRef.get();
                    if (config.enableTaskExecution && nextExecTime != null
                        && (config.pollInterval < 0 || nextExecTime <= new Date().getTime() + config.pollInterval)) {

                        expectedExecTime = nextExecTime;
                        long delay = nextExecTime - new Date().getTime();

                        ScheduledExecutorService executor = persistentExecutor.scheduledExecutor;
                        if (executor == null) {
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                                Tr.debug(this, tc, "deactivated - reschedule skipped");
                        } else
                            executor.schedule(this, delay, TimeUnit.MILLISECONDS);
                    } else if (ownerForDeferredTask != null)
                        appTracker.deferTask(this, ownerForDeferredTask, persistentExecutor);
                    else {
                        persistentExecutor.inMemoryTaskIds.remove(taskId);
                        if (failure != null) {
                            taskName = taskName == null || taskName.length() == 0 || taskName.length() == 1 && taskName.charAt(0) == ' ' ? String.valueOf(taskId) // empty task name
                                            : taskId + " (" + taskName + ")";
                            Tr.warning(tc, "CWWKC1511.retry.limit.reached.failed", persistentExecutor.name, taskName, nextFailureCount, failure);
                        }
                    }
                }
            } catch (Throwable x) {
                if (failure != null)
                    failure = x;

                // Retry the task if an error occurred
                processRetryableTaskFailure(failure, loader, nextFailureCount, config, taskName);
            }
        }

        if (trace && tc.isEntryEnabled())
            Tr.exit(this, tc, "run[" + taskId + ']', failure);
    }
215623
public function run(array $args = [], $enableLog = false)
    {
        try {
            return $this->workflow->run($args, $enableLog);
        } catch (WorkflowException $ex) {
            throw new StateMachineException('Error running State Machine', 100, $ex);
        }
    }
842866
public void locked (@Nonnull final Runnable aRunnable)
  {
    ValueEnforcer.notNull (aRunnable, "Runnable");

    lock ();
    try
    {
      aRunnable.run ();
    }
    finally
    {
      unlock ();
    }
  }
599372
@SuppressWarnings("unchecked")
    public void runDeadlockFuture(Runnable deadlockGuardTask) {
        if (deadlockFuture == null) {
            ThreadPoolTaskScheduler deadlockGuard = conn.getDeadlockGuardScheduler();
            if (deadlockGuard != null) {
                try {
                    deadlockFuture = (ScheduledFuture<Runnable>) deadlockGuard.schedule(deadlockGuardTask, new Date(packet.getExpirationTime()));
                } catch (TaskRejectedException e) {
                    log.warn("DeadlockGuard task is rejected for {}", sessionId, e);
                }
            } else {
                log.debug("Deadlock guard is null for {}", sessionId);
            }
        } else {
            log.warn("Deadlock future is already create for {}", sessionId);
        }
    }
342014
public boolean schedulePolling() {
        if(isDisabled())    return false;
        SCMTrigger scmt = getTrigger(SCMTrigger.class);
        if(scmt==null)      return false;
        scmt.run();
        return true;
    }
1176809
protected RunnerResult doRun(Class<? extends LaJob> jobType, LaJobRuntime runtime) {
        // similar to async manager's process
        arrangeThreadCacheContext(runtime);
        arrangePreparedAccessContext(runtime);
        arrangeCallbackContext(runtime);
        final Object variousPreparedObj = prepareVariousContext(runtime);
        final long before = showRunning(runtime);
        Throwable cause = null;
        try {
            debugFw(runtime, "...Calling try clause of job runner");
            hookBefore(runtime);
            debugFw(runtime, "...Calling actuallyRun() of job runner");
            actuallyRun(jobType, runtime);
        } catch (Throwable e) {
            debugFw(runtime, "...Calling catch clause of job runner: {}", e.getClass().getSimpleName());
            final Throwable filtered = filterCause(e);
            cause = filtered;
            showJobException(runtime, before, filtered);
        } finally {
            debugFw(runtime, "...Calling finally clause of job runner");
            hookFinally(runtime, OptionalThing.ofNullable(cause, () -> {
                throw new IllegalStateException("Not found the cause: " + runtime);
            }));
            showFinishing(runtime, before, cause); // should be before clearing because of using them
            clearVariousContext(runtime, variousPreparedObj);
            clearPreparedAccessContext();
            clearCallbackContext();
            clearThreadCacheContext();
        }
        debugFw(runtime, "...Calling createRunnerResult() of job runner");
        return createRunnerResult(runtime, cause);
    }
227917
protected function __lock()
    {
        $beginTime = microtime(true);
        do {
            if($this->__tryLock())
            {
                return true;
            }
            if(0 === $this->waitTimeout || microtime(true) - $beginTime < $this->waitTimeout / 1000)
            {
                if(Coroutine::isIn())
                {
                    Coroutine::sleep($this->waitSleepTime / 1000);
                }
                else
                {
                    usleep($this->waitSleepTime * 1000);
                }
            }
            else
            {
                break;
            }
        } while(true);
        return false;
    }
70876
public function work($interval = ResqueWorkerBase::DEFAULT_INTERVAL, $blocking = false)
    {
        if ($interval !== null) {
            $this->interval = $interval;
        }

        $this->updateProcLine('Starting');
        $this->startup();

        while (true) {
            if (function_exists('pcntl_signal_dispatch')) {
                pcntl_signal_dispatch();
            }
            if ($this->shutdown) {
                break;
            }

            // Attempt to find and reserve a job
            $job = false;
            if (!$this->paused) {
                if ($blocking === true) {
                    $this->logger->log(
                        LogLevel::INFO,
                        'Starting blocking with timeout of {interval}',
                        ['interval' => $this->interval]
                    );
                    $this->updateProcLine(
                        'Waiting for ' . implode(',', $this->queues) . ' with blocking timeout ' . $this->interval
                    );
                } else {
                    $this->updateProcLine(
                        'Waiting for ' . implode(',', $this->queues) . ' with interval ' . $this->interval);
                }

                $job = $this->reserve($blocking, $this->interval);
            }

            if (!$job) {
                // For an interval of 0, break now - helps with unit testing etc
                if ($this->interval == 0) {
                    break;
                }

                if ($blocking === false) {
                    // If no job was found, we sleep for $this->interval before continuing and checking again
                    $this->logger->log(LogLevel::INFO, 'Sleeping for {interval}', ['interval' => $this->interval]);
                    if ($this->paused) {
                        $this->updateProcLine('Paused');
                    } else {
                        $this->updateProcLine('Waiting for ' . implode(',', $this->queues));
                    }

                    usleep($this->interval * 1000000);
                }

                continue;
            }

            $this->logger->log(LogLevel::NOTICE, 'Starting work on {job}', ['job' => $job]);
            $this->resqueInstance->events->trigger('beforeFork', $job);
            $this->workingOn($job);

            $this->child = $this->resqueInstance->fork();

            // Forked and we're the child. Run the job.
            if ($this->child === 0 || $this->child === false) {
                $status = 'Processing ' . $job->queue . ' since ' . date('d/m/Y h:i:s a');
                $this->updateProcLine($status);
                $this->logger->log(LogLevel::INFO, $status);
                $this->perform($job);
                if ($this->child === 0) {
                    exit(0);
                }
            }

            if ($this->child > 0) {
                // Parent process, sit and wait
                $status = 'Forked ' . $this->child . ' at ' . date('d/m/Y h:i:s a');
                $this->updateProcLine($status);
                $this->logger->log(LogLevel::INFO, $status);

                // Wait until the child process finishes before continuing
                pcntl_wait($status);
                $exitStatus = pcntl_wexitstatus($status);
                if ($exitStatus !== 0) {
                    $job->fail(new ResqueJobForceExitException(
                        'Job exited with exit code ' . $exitStatus
                    ));
                }
            }

            $this->child = null;
            $this->doneWorking();
        }

        $this->unregisterWorker();
    }
1294355
public synchronized void runNow(String scheduledJobId) {
    ScheduledJob scheduledJob = getJob(scheduledJobId);

    try {
      JobKey jobKey = new JobKey(scheduledJobId, SCHEDULED_JOB_GROUP);
      if (quartzScheduler.checkExists(jobKey)) {
        // Run job now
        quartzScheduler.triggerJob(jobKey);
      } else {
        // Schedule with 'now' trigger
        Trigger trigger =
            newTrigger().withIdentity(scheduledJobId, SCHEDULED_JOB_GROUP).startNow().build();
        schedule(scheduledJob, trigger);
      }
    } catch (SchedulerException e) {
      LOG.error("Error runNow ScheduledJob", e);
      throw new MolgenisDataException("Error job runNow", e);
    }
  }