java 如何使用 Spring(和 Quartz)动态启动计划作业?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36267127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:10:43  来源:igfitidea点击:

How to start scheduled jobs dynamically with Spring (and Quartz)?

javaspringquartz-scheduler

提问by

I'm following thistutorial to schedule jobs with Spring.

我正在按照教程使用 Spring 安排作业。

In the tutorial scheduling is started by the following code:

在教程中调度是由以下代码启动的:

public static void main(String args[]){
    AbstractApplicationContext context = new ClassPathXmlApplicationContext("app-config.xml");
}

Instead of using main, i'd like to start jobs with a method that can be called from anywhere in my application, for example:

我不想使用 main,而是使用一种可以从我的应用程序中的任何地方调用的方法开始作业,例如:

public void startJobs() {
    // what should this method do to start the jobs?
}

Can the following work?

以下可以吗?

public void startJobs() {
    AbstractApplicationContext context = new ClassPathXmlApplicationContext("app-config.xml");
}

Is this considered good practice?

这被认为是好的做法吗?

Basically what i want to achieve is to be able to start the jobs whenever i want (whenever i call the startJobs()method), not on startup in the main method.

基本上我想要实现的是能够在我想要的时候(每当我调用startJobs()方法时)开始工作,而不是在主方法中启动。

How can i do this?

我怎样才能做到这一点?

回答by Dinesh

Have you done with scheduling using quartz and spring. If yes, is it running fine? The example link you shared belongs to "The Task Namespace"

您是否完成了使用石英和弹簧的调度。如果是,它运行正常吗?您分享的示例链接属于“任务命名空间”

Quartz uses Trigger, Job and JobDetail objects to realize scheduling of all kinds of jobs. For the basic concepts behind Quartz, have a look at

Quartz 使用 Trigger、Job 和 JobDetail 对象来实现各种作业的调度。对于 Quartz 背后的基本概念,请查看

http://quartz-scheduler.org/documentation/quartz-2.2.x/quick-start

http://quartz-scheduler.org/documentation/quartz-2.2.x/quick-start

To integrate it with Spring, Please have a look at this also

要将它与 Spring 集成,请也看看这个

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html#scheduling-quartz-jobdetail

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html#scheduling-quartz-jobdetail

XML Configuration of Spring and quartz.

Spring和quartz的XML配置。

<bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
        <property name="jobRepository" ref="jobRepository" />
</bean>
    <bean
        class="org.springframework.batch.core.configuration.support.JobRegistryBeanPostProcessor">
        <property name="jobRegistry" ref="jobRegistry" />
    </bean>

    <bean id="jobRegistry"
        class="org.springframework.batch.core.configuration.support.MapJobRegistry" />

    <bean name="csvLoaderJobDetail"
        class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <property name="jobClass" value="com.example.CSVloader.ScheduledJob" />
        <property name="jobDataMap">
            <map>
                <entry key="csvData" value="value1" />
                <entry key="date" value="25/09/2015" />
                <entry key="csvId" value="1" />
                <entry key="jobName" value="csvLoadJob" />
                <entry key="jobLocator" value-ref="jobRegistry" />
                <entry key="jobLauncher" value-ref="jobLauncher" />
            </map>
        </property>
        <property name="durability" value="true" />
    </bean>

    <bean id="csvLoaderTrigger"
        class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="csvLoaderJobDetail" />
        <property name="cronExpression" value="0 0 12 * * ?" />
    </bean>

    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="jobDetails">
            <list>
                <ref bean="csvLoaderJobDetail" />
            </list>
        </property>
        <property name="triggers">
            <list>
                <ref bean="csvLoaderTrigger" />
            </list>
        </property>
        <property name="quartzProperties">
            <props>
                <prop key="org.quartz.scheduler.skipUpdateCheck">true</prop>
            </props>
        </property>
    </bean>

To fire the job manually, you need to inject SchedulerFactoryBean in your spring bean. First you need to get all the jobs created in quartz scheduler, then you can trigger any job manually by using Job Key and Job group of each job.

要手动触发作业,您需要在 Spring bean 中注入 SchedulerFactoryBean。首先,您需要获取在quartz 调度程序中创建的所有作业,然后您可以使用每个作业的作业键和作业组手动触发任何作业。

    @Autowired
    private SchedulerFactoryBean schedulerFactory;

    org.quartz.Scheduler scheduler = schedulerFactory.getScheduler();

    // loop jobs by group
    for (String groupName : scheduler.getJobGroupNames()) {

           // get jobkey
           for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher
    .jobGroupEquals(groupName))) {

               String jobName = jobKey.getName();
               String jobGroup = jobKey.getGroup();

               scheduler.triggerJob(jobName,  jobGroup);
            }
    }

Now you can create a list of Object, which contain jobName and jobGroup to trigger any job manually.

现在您可以创建一个 Object 列表,其中包含 jobName 和 jobGroup 以手动触发任何作业。

回答by Naruto

A better and easy way , use @Scheduled annotation.

一个更好更简单的方法,使用@Scheduled 注释。

Method 1) Task scheduling using fixed delay attribute in @Scheduled annotation

方法一)在@Scheduled注解中使用固定延迟属性进行任务调度

 @Scheduled(fixedDelay = 5000)

Method 2) Task scheduling using cron expression in @Scheduled annotation

方法2)在@Scheduled注解中使用cron表达式进行任务调度

 @Scheduled(cron="*/5 * * * * ?")

Method 3) Task scheduling using cron expression from properties file

方法 3) 使用属性文件中的 cron 表达式进行任务调度

@Scheduled(cron = "${cron.expression}")

You can get complete example here

你可以在这里得到完整的例子