如何以编程方式创建spring预定作业?

时间:2017-03-22 07:14:31

标签: java spring quartz-scheduler spring-4

我有一个如下定义的弹簧调度程序。我想以编程方式创建此调度程序。

我真正想做的是我想从我的数据库中获取cronExpression并动态创建executorJob和Trigger并将它们添加到jobdetails和触发器。我不需要动态创建quartzProperties,因为它们不会发生变化。有没有办法做到这一点?

<bean id="testExecutorJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
    <property name="targetObject" ref="testExecutor" />
    <property name="targetMethod" value="runTest" />
</bean>

<bean id="testTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
    <property name="jobDetail" ref="testExecutorJob" />
    <property name="cronExpression" value="0 0 0/3 1/1 * ? *" />
</bean>

<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="overwriteExistingJobs" value="true"/>
    <property name="autoStartup" value="true" />
    <property name="quartzProperties">
        <props>
            <prop key="org.quartz.scheduler.instanceName">MyScheduler</prop>
            <prop key="org.quartz.scheduler.instanceId">AUTO</prop>
            <prop key="org.quartz.scheduler.skipUpdateCheck">true</prop>
            <prop key="org.quartz.jobStore.misfireThreshold">60000</prop>
            <prop key="org.quartz.jobStore.class">org.quartz.simpl.RAMJobStore</prop>
            <prop key="org.quartz.threadPool.class">org.quartz.simpl.SimpleThreadPool</prop>
            <prop key="org.quartz.threadPool.threadCount">5</prop>                
        </props>
    </property>
    <property name="jobDetails">
        <list>
            <ref bean="testExecutorJob" />
        </list>
    </property>
    <property name="triggers">
        <list>
            <ref bean="testTrigger" />
        </list>
    </property>
</bean>

1 个答案:

答案 0 :(得分:1)

这是我如何运行一些工作的例子

        sched = new StdSchedulerFactory().getScheduler();
        sched.start();

//创建一份工作

        JobDetail job = JobBuilder.newJob(myClass.class)
                    .withIdentity("cronjob", "crongroup")
                    .usingJobData("param1", "someparam")
                    .build();

//创建触发器

        Trigger trigger = trigger = TriggerBuilder
                            .newTrigger()
                            .withSchedule(CronScheduleBuilder.cronSchedule(cronString))
                            .build();

// scheule it

        sched.scheduleJob(job, trigger);