Search in sources :

Example 11 with Job

use of org.quartz.Job in project BRFS by zhangnianli.

the class QuartzBaseSchedulers method addTask.

@Override
public boolean addTask(T task) throws Exception {
    if (!checkTask(task)) {
        return false;
    }
    // 1.设置job的名称及执行的class
    Class<? extends Job> clazz = (Class<? extends Job>) Class.forName(task.getClassInstanceName());
    String taskName = task.getTaskName();
    String taskGroup = task.getTaskGroupName();
    JobBuilder jobBuilder = JobBuilder.newJob(clazz).withIdentity(taskName, taskGroup);
    // 2.设置任务需要的数据
    Map<String, String> tmp = task.getTaskContent();
    if (tmp != null && !tmp.isEmpty()) {
        JobDataMap jobData = new JobDataMap();
        jobData.putAll(tmp);
        jobBuilder.usingJobData(jobData);
    }
    // 3.生成jobDetail
    JobDetail jobDetail = jobBuilder.build();
    // 4.判断触发器的类型 0 cron任务,1 simple任务
    int taskType = task.getTaskKind();
    String cycleContent = task.getCycleContent();
    Trigger trigger = null;
    if (taskType == 0) {
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cycleContent);
        trigger = TriggerBuilder.newTrigger().withIdentity(taskName, taskGroup).withSchedule(cronScheduleBuilder).build();
    } else if (taskType == 1) {
        String[] cycles = StringUtils.getSplit(cycleContent, ",");
        if (cycles == null || cycles.length == 0) {
            throw new NullPointerException("simple trigger cycle time is empty !!! content : " + cycleContent);
        }
        if (cycles.length != 2) {
            throw new NullPointerException("simple trigger cycle time is error !!! content : " + cycleContent);
        }
        long interval = Long.valueOf(cycles[0]);
        int repeateCount = Integer.valueOf(cycles[1]);
        SimpleScheduleBuilder sSched = SimpleScheduleBuilder.simpleSchedule().withIntervalInMilliseconds(interval).withRepeatCount(repeateCount);
        trigger = TriggerBuilder.newTrigger().withIdentity(taskName, taskGroup).startNow().withSchedule(sSched).build();
    }
    if (trigger == null || jobDetail == null) {
        return false;
    }
    Scheduler scheduler = this.ssf.getScheduler(this.instanceName);
    scheduler.scheduleJob(jobDetail, trigger);
    return true;
}
Also used : JobDataMap(org.quartz.JobDataMap) CronScheduleBuilder(org.quartz.CronScheduleBuilder) Scheduler(org.quartz.Scheduler) JobBuilder(org.quartz.JobBuilder) SimpleScheduleBuilder(org.quartz.SimpleScheduleBuilder) JobDetail(org.quartz.JobDetail) Trigger(org.quartz.Trigger) SimpleTrigger(org.quartz.SimpleTrigger) CronTrigger(org.quartz.CronTrigger) Job(org.quartz.Job)

Example 12 with Job

use of org.quartz.Job in project pentaho-platform by pentaho.

the class ActionAdapterQuartzJob method invokeAction.

/**
 * Invokes the {@link IAction} bean that is created from the provided {@code actionClassName} and {@code actionId} as
 * the provided {@code actionUser}. If the {@code IAction} execution fails as-is, the scheduler attempts to re-create
 * the job that will try to invoke the {@link IAction} again.
 *
 * @param actionClassName The class name of the {@link IAction} bean; used as a backup, if the {@code actionId} is not
 *                        available or vald
 * @param actionId        The bean id of the {@link IAction} requested to be invoked.
 * @param actionUser      The user invoking the {@link IAction}
 * @param context         the {@code JobExecutionContext}
 * @param params          the {@link Map} or parameters needed to invoke the {@link IAction}
 * @throws Exception when the {@code IAction} cannot be invoked for some reason.
 */
protected void invokeAction(final String actionClassName, final String actionId, final String actionUser, final JobExecutionContext context, final Map<String, Serializable> params) throws Exception {
    final String workItemUid = ActionUtil.extractUid(params);
    WorkItemLifecycleEventUtil.publish(workItemUid, params, WorkItemLifecyclePhase.SUBMITTED);
    // creates an instance of IActionInvoker, which knows how to invoke this IAction - if the IActionInvoker bean is
    // not defined through spring, fall back on the default action invoker
    final IActionInvoker actionInvoker = Optional.ofNullable(PentahoSystem.get(IActionInvoker.class)).orElse(getActionInvoker());
    // Instantiate the requested IAction bean
    final IAction actionBean = (IAction) ActionUtil.createActionBean(actionClassName, actionId);
    if (actionInvoker == null || actionBean == null) {
        final String failureMessage = Messages.getInstance().getErrorString(// $NON-NLS-1$
        "ActionAdapterQuartzJob.ERROR_0002_FAILED_TO_CREATE_ACTION", getActionIdentifier(null, actionClassName, actionId), StringUtil.getMapAsPrettyString(params));
        WorkItemLifecycleEventUtil.publish(workItemUid, params, WorkItemLifecyclePhase.FAILED, failureMessage);
        throw new LoggingJobExecutionException(failureMessage);
    }
    if (actionBean instanceof BlockoutAction) {
        params.put(IBlockoutManager.SCHEDULED_FIRE_TIME, context.getScheduledFireTime());
    }
    // Invoke the action and get the status of the invocation
    final IActionInvokeStatus status = actionInvoker.invokeAction(actionBean, actionUser, getSerializableMap(params));
    // Status may not be available for remote execution, which is expected
    if (status == null) {
        if (log.isWarnEnabled()) {
            log.warn(Messages.getInstance().getErrorString(// $NON-NLS-1$
            "ActionAdapterQuartzJob.WARN_0002_NO_STATUS", getActionIdentifier(actionBean, actionClassName, actionId), StringUtil.getMapAsPrettyString(params)));
        }
        return;
    }
    // exception
    if (!status.isExecutionSuccessful()) {
        // throw job exception
        throw new JobExecutionException(Messages.getInstance().getActionFailedToExecute(// $NON-NLS-1$
        actionBean.getClass().getName()));
    }
    final boolean requiresUpdate = status.requiresUpdate();
    final Throwable throwable = status.getThrowable();
    Object objsp = status.getStreamProvider();
    IBackgroundExecutionStreamProvider sp = null;
    if (objsp != null && IBackgroundExecutionStreamProvider.class.isAssignableFrom(objsp.getClass())) {
        sp = (IBackgroundExecutionStreamProvider) objsp;
    }
    final IBackgroundExecutionStreamProvider streamProvider = sp;
    // shallow copy
    final Map<String, Serializable> jobParams = new HashMap<String, Serializable>(params);
    final IScheduler scheduler = PentahoSystem.getObjectFactory().get(IScheduler.class, "IScheduler2", null);
    if (throwable != null) {
        Object restartFlag = jobParams.get(QuartzScheduler.RESERVEDMAPKEY_RESTART_FLAG);
        if (restartFlag == null) {
            final SimpleJobTrigger trigger = new SimpleJobTrigger(new Date(), null, 0, 0);
            final Class<IAction> iaction = (Class<IAction>) actionBean.getClass();
            // recreate the job in the context of the original creator
            SecurityHelper.getInstance().runAsUser(actionUser, new Callable<Void>() {

                @Override
                public Void call() throws Exception {
                    if (streamProvider != null) {
                        // remove generated content
                        streamProvider.setStreamingAction(null);
                    }
                    QuartzJobKey jobKey = QuartzJobKey.parse(context.getJobDetail().getName());
                    String jobName = jobKey.getJobName();
                    jobParams.put(QuartzScheduler.RESERVEDMAPKEY_RESTART_FLAG, Boolean.TRUE);
                    WorkItemLifecycleEventUtil.publish(workItemUid, params, WorkItemLifecyclePhase.RESTARTED);
                    scheduler.createJob(jobName, iaction, jobParams, trigger, streamProvider);
                    log.warn("New RunOnce job created for " + jobName + " -> possible startup synchronization error");
                    return null;
                }
            });
        } else {
            log.warn("RunOnce already created, skipping");
        }
        throw new JobExecutionException(throwable);
    }
    scheduler.fireJobCompleted(actionBean, actionUser, params, streamProvider);
    if (requiresUpdate) {
        log.warn("Output path for job: " + context.getJobDetail().getName() + " has changed. Job requires update");
        try {
            final IJobTrigger trigger = scheduler.getJob(context.getJobDetail().getName()).getJobTrigger();
            final Class<IAction> iaction = (Class<IAction>) actionBean.getClass();
            // remove job with outdated/invalid output path
            scheduler.removeJob(context.getJobDetail().getName());
            // recreate the job in the context of the original creator
            SecurityHelper.getInstance().runAsUser(actionUser, new Callable<Void>() {

                @Override
                public Void call() throws Exception {
                    // remove generated content
                    streamProvider.setStreamingAction(null);
                    QuartzJobKey jobKey = QuartzJobKey.parse(context.getJobDetail().getName());
                    String jobName = jobKey.getJobName();
                    WorkItemLifecycleEventUtil.publish(workItemUid, params, WorkItemLifecyclePhase.RESTARTED);
                    org.pentaho.platform.api.scheduler2.Job j = scheduler.createJob(jobName, iaction, jobParams, trigger, streamProvider);
                    log.warn("New Job: " + j.getJobId() + " created");
                    return null;
                }
            });
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug(MessageFormat.format("Scheduling system successfully invoked action {0} as user {1} with params [ {2} ]", // $NON-NLS-1$
        actionBean.getClass().getName(), actionUser, QuartzScheduler.prettyPrintMap(params)));
    }
}
Also used : IBackgroundExecutionStreamProvider(org.pentaho.platform.api.scheduler2.IBackgroundExecutionStreamProvider) Serializable(java.io.Serializable) HashMap(java.util.HashMap) BlockoutAction(org.pentaho.platform.scheduler2.blockout.BlockoutAction) JobExecutionException(org.quartz.JobExecutionException) Job(org.quartz.Job) IAction(org.pentaho.platform.api.action.IAction) IActionInvoker(org.pentaho.platform.api.action.IActionInvoker) Date(java.util.Date) JobExecutionException(org.quartz.JobExecutionException) SimpleJobTrigger(org.pentaho.platform.api.scheduler2.SimpleJobTrigger) IActionInvokeStatus(org.pentaho.platform.api.action.IActionInvokeStatus) IJobTrigger(org.pentaho.platform.api.scheduler2.IJobTrigger) IScheduler(org.pentaho.platform.api.scheduler2.IScheduler)

Example 13 with Job

use of org.quartz.Job in project syncope by apache.

the class JobManagerImpl method register.

@Override
public Map<String, Object> register(final SchedTask task, final Date startAt, final long interruptMaxRetries) throws SchedulerException {
    TaskJob job = createSpringBean(TaskJob.class);
    job.setTaskKey(task.getKey());
    Implementation jobDelegate = task.getJobDelegate() == null ? task instanceof PullTask ? implementationDAO.find(ImplementationType.TASKJOB_DELEGATE).stream().filter(impl -> PullJobDelegate.class.getName().equals(impl.getBody())).findFirst().orElse(null) : task instanceof PushTask ? implementationDAO.find(ImplementationType.TASKJOB_DELEGATE).stream().filter(impl -> PushJobDelegate.class.getName().equals(impl.getBody())).findFirst().orElse(null) : null : task.getJobDelegate();
    if (jobDelegate == null) {
        throw new IllegalArgumentException("Task " + task + " does not provide any " + SchedTaskJobDelegate.class.getSimpleName());
    }
    Map<String, Object> jobMap = new HashMap<>();
    jobMap.put(JobManager.DOMAIN_KEY, AuthContextUtils.getDomain());
    jobMap.put(TaskJob.DELEGATE_IMPLEMENTATION, jobDelegate.getKey());
    registerJob(JobNamer.getJobKey(task).getName(), job, task.getCronExpression(), startAt, jobMap);
    return jobMap;
}
Also used : Connection(java.sql.Connection) SyncopeLoader(org.apache.syncope.core.persistence.api.SyncopeLoader) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) AbstractBeanDefinition(org.springframework.beans.factory.support.AbstractBeanDefinition) StringUtils(org.apache.commons.lang3.StringUtils) CPlainAttr(org.apache.syncope.core.persistence.api.entity.conf.CPlainAttr) JobBuilder(org.quartz.JobBuilder) Scheduler(org.quartz.Scheduler) Pair(org.apache.commons.lang3.tuple.Pair) ResultSet(java.sql.ResultSet) Map(java.util.Map) AuthContextUtils(org.apache.syncope.core.spring.security.AuthContextUtils) SchedulerFactoryBean(org.springframework.scheduling.quartz.SchedulerFactoryBean) ImplementationDAO(org.apache.syncope.core.persistence.api.dao.ImplementationDAO) PullJobDelegate(org.apache.syncope.core.provisioning.java.pushpull.PullJobDelegate) Constants(org.quartz.impl.jdbcjobstore.Constants) Task(org.apache.syncope.core.persistence.api.entity.task.Task) SchedTaskJobDelegate(org.apache.syncope.core.provisioning.api.job.SchedTaskJobDelegate) JobNamer(org.apache.syncope.core.provisioning.api.job.JobNamer) Set(java.util.Set) Implementation(org.apache.syncope.core.persistence.api.entity.Implementation) PreparedStatement(java.sql.PreparedStatement) NotFoundException(org.apache.syncope.core.persistence.api.dao.NotFoundException) JobDataMap(org.quartz.JobDataMap) Optional(java.util.Optional) TriggerKey(org.quartz.TriggerKey) ConfDAO(org.apache.syncope.core.persistence.api.dao.ConfDAO) DataSourceUtils(org.springframework.jdbc.datasource.DataSourceUtils) IOUtil(org.identityconnectors.common.IOUtil) HashMap(java.util.HashMap) Job(org.quartz.Job) JobKey(org.quartz.JobKey) TaskDAO(org.apache.syncope.core.persistence.api.dao.TaskDAO) HashSet(java.util.HashSet) SQLException(java.sql.SQLException) PullTask(org.apache.syncope.core.persistence.api.entity.task.PullTask) SchedulerException(org.quartz.SchedulerException) TriggerBuilder(org.quartz.TriggerBuilder) BeanCreationException(org.springframework.beans.factory.BeanCreationException) DataSource(javax.sql.DataSource) ImplementationType(org.apache.syncope.common.lib.types.ImplementationType) SchedTask(org.apache.syncope.core.persistence.api.entity.task.SchedTask) ReportJob(org.apache.syncope.core.provisioning.java.job.report.ReportJob) SyncopeConstants(org.apache.syncope.common.lib.SyncopeConstants) PushJobDelegate(org.apache.syncope.core.provisioning.java.pushpull.PushJobDelegate) Report(org.apache.syncope.core.persistence.api.entity.Report) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) NotificationJob(org.apache.syncope.core.provisioning.java.job.notification.NotificationJob) ReportDAO(org.apache.syncope.core.persistence.api.dao.ReportDAO) JobManager(org.apache.syncope.core.provisioning.api.job.JobManager) PushTask(org.apache.syncope.core.persistence.api.entity.task.PushTask) DomainsHolder(org.apache.syncope.core.persistence.api.DomainsHolder) ApplicationContextProvider(org.apache.syncope.core.spring.ApplicationContextProvider) TaskType(org.apache.syncope.common.lib.types.TaskType) CronScheduleBuilder(org.quartz.CronScheduleBuilder) Transactional(org.springframework.transaction.annotation.Transactional) PushJobDelegate(org.apache.syncope.core.provisioning.java.pushpull.PushJobDelegate) HashMap(java.util.HashMap) PullTask(org.apache.syncope.core.persistence.api.entity.task.PullTask) PushTask(org.apache.syncope.core.persistence.api.entity.task.PushTask) Implementation(org.apache.syncope.core.persistence.api.entity.Implementation)

Example 14 with Job

use of org.quartz.Job in project candlepin by candlepin.

the class HighlanderFactoryTest method testNewJob.

@Test
public void testNewJob() throws SchedulerException, ParseException {
    assertNotNull(hf);
    try {
        hf.newJob(null, null);
        fail("should've died with npe");
    } catch (NullPointerException npe) {
    // Expected
    }
    String crontab = "0 0 12 * * ?";
    JobDetail jd = newJob(TestJob.class).withIdentity("testjob", "group").build();
    Trigger trigger = newTrigger().withIdentity("testjob", "group").withSchedule(cronSchedule(crontab)).build();
    TriggerFiredBundle tfb = new TriggerFiredBundle(jd, (OperableTrigger) trigger, null, false, null, null, null, null);
    Job j = hf.newJob(tfb, null);
    assertNotNull(j);
}
Also used : JobDetail(org.quartz.JobDetail) OperableTrigger(org.quartz.spi.OperableTrigger) TriggerBuilder.newTrigger(org.quartz.TriggerBuilder.newTrigger) Trigger(org.quartz.Trigger) TriggerFiredBundle(org.quartz.spi.TriggerFiredBundle) JobBuilder.newJob(org.quartz.JobBuilder.newJob) Job(org.quartz.Job) Test(org.junit.Test)

Example 15 with Job

use of org.quartz.Job in project BRFS by zhangnianli.

the class DefaultBaseSchedulers method addTask.

@Override
public boolean addTask(SumbitTaskInterface task) throws ParamsErrorException {
    // 1.检查任务的有效性
    checkTask(task);
    // 2.线程池处于暂停时,不提交任务
    if (this.pausePoolFlag) {
        LOG.warn("Thread pool is paused !!!");
        return false;
    }
    try {
        Scheduler scheduler = this.ssf.getScheduler(this.instanceName);
        // 当线程池不处于运行时,将不添加任务
        if (!isNormal()) {
            LOG.warn("Thread pool is not normal");
            return false;
        }
        // 当线程池满了也不会添加任务
        if (this.poolSize <= getSumbitTaskCount()) {
            LOG.warn("thread pool is full !!!");
            return false;
        }
        // 1.设置job的名称及执行的class
        Class<? extends Job> clazz = (Class<? extends Job>) Class.forName(task.getClassInstanceName());
        String taskName = task.getTaskName();
        String taskGroup = task.getTaskGroupName();
        JobBuilder jobBuilder = JobBuilder.newJob(clazz).withIdentity(taskName, taskGroup);
        // 2.设置任务需要的数据
        Map<String, String> tmp = task.getTaskContent();
        if (tmp != null && !tmp.isEmpty()) {
            JobDataMap jobData = new JobDataMap();
            jobData.putAll(tmp);
            jobBuilder.usingJobData(jobData);
        }
        // 3.生成jobDetail
        JobDetail jobDetail = jobBuilder.build();
        // 4.判断触发器的类型 0 cron任务,1 simple任务
        int taskType = task.getTaskKind();
        String cycleContent = task.getCycleContent();
        Trigger trigger = null;
        if (taskType == 0) {
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cycleContent);
            trigger = TriggerBuilder.newTrigger().withIdentity(taskName, taskGroup).withSchedule(cronScheduleBuilder).build();
        } else if (taskType == 1) {
            String[] cycles = BrStringUtils.getSplit(cycleContent, ",");
            if (cycles == null || cycles.length == 0) {
                throw new NullPointerException("simple trigger cycle time is empty !!! content : " + cycleContent);
            }
            if (cycles.length != 5) {
                throw new NullPointerException("simple trigger cycle time is error !!! content : " + cycleContent);
            }
            long interval = Long.parseLong(cycles[0]);
            int repeateCount = Integer.parseInt(cycles[1]);
            repeateCount = repeateCount - 1;
            long delayTime = Long.parseLong(cycles[2]);
            boolean rightNow = Boolean.valueOf(cycles[3]);
            boolean cycleFlag = Boolean.valueOf(cycles[4]);
            SimpleScheduleBuilder builder = SimpleScheduleBuilder.simpleSchedule();
            builder.withIntervalInMilliseconds(interval);
            if (cycleFlag) {
                builder.repeatForever();
            } else if (repeateCount >= 0) {
                builder.withRepeatCount(repeateCount);
            } else {
                LOG.warn("repeated count is zero !!!!");
                return false;
            }
            TriggerBuilder trigBuilder = TriggerBuilder.newTrigger().withIdentity(taskName, taskGroup).withSchedule(builder);
            if (!rightNow && delayTime > 0) {
                long current = System.currentTimeMillis() + delayTime;
                Date date = new Date(current);
                trigBuilder.startAt(date);
            } else {
                trigBuilder.startNow();
            }
            trigger = trigBuilder.build();
        }
        if (trigger == null || jobDetail == null) {
            LOG.warn(" create task message is null");
            return false;
        }
        scheduler.scheduleJob(jobDetail, trigger);
        return true;
    } catch (NumberFormatException | ClassNotFoundException | ParseException | SchedulerException e) {
        LOG.error("add task {}", e);
    }
    return false;
}
Also used : JobDataMap(org.quartz.JobDataMap) CronScheduleBuilder(org.quartz.CronScheduleBuilder) SchedulerException(org.quartz.SchedulerException) Scheduler(org.quartz.Scheduler) JobBuilder(org.quartz.JobBuilder) SimpleScheduleBuilder(org.quartz.SimpleScheduleBuilder) TriggerBuilder(org.quartz.TriggerBuilder) Date(java.util.Date) JobDetail(org.quartz.JobDetail) Trigger(org.quartz.Trigger) ParseException(java.text.ParseException) Job(org.quartz.Job)

Aggregations

Job (org.quartz.Job)17 JobDetail (org.quartz.JobDetail)9 JobDataMap (org.quartz.JobDataMap)6 SchedulerException (org.quartz.SchedulerException)5 Trigger (org.quartz.Trigger)5 CronScheduleBuilder (org.quartz.CronScheduleBuilder)4 JobBuilder (org.quartz.JobBuilder)4 Date (java.util.Date)3 Scheduler (org.quartz.Scheduler)3 Serializable (java.io.Serializable)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 JobExecutionContext (org.quartz.JobExecutionContext)2 JobKey (org.quartz.JobKey)2 SimpleScheduleBuilder (org.quartz.SimpleScheduleBuilder)2 TriggerBuilder (org.quartz.TriggerBuilder)2 Logger (org.slf4j.Logger)2 ScheduleTrigger (com.monitor.model.task.ScheduleTrigger)1 Values (com.searchcode.app.config.Values)1 IRepo (com.searchcode.app.dao.IRepo)1