Saltar al contenido

Ejemplo de Java: programación dinámica de trabajos con Quartz

Solución:

Código de ejemplo para la programación de trabajos de Dynamic Quartz:

Dependencias de Maven

         <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>1.8.5</version>
         </dependency>
            <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

Archivo de contexto de la aplicación (dynamic-jobs.xml)

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springmodules.org/schema/ehcache http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd">


    <!-- The Task Bean-->
    <bean id="myTask" class="com.xxx.example.dynamicjob.MyTask" />

    <!-- The quartz scheduler configuration -->
    <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"/>

</beans>

Clase Java para tareas

package com.xxx.example.dynamicjob;

    public class MyTask
    {
        public void performAction() {
            System.out.println("Hey, you reached me...:)");
        }          
    }

Clase Java para crear trabajo dinámico

package com.xxx.example.dynamicjob;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.CronTriggerBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;

public class DynamicJobExample {

    /**
    * @param args
    */
    public static void main(String[] args) {

                ClassPathResource res = new ClassPathResource("dynamic-jobs.xml");
                XmlBeanFactory factory = new XmlBeanFactory(res);

                //get the quartzFactory bean
                Scheduler scheduler = (Scheduler) factory.getBean("scheduler");

                //get the task bean
                MyTask myTask = (MyTask) factory.getBean("myTask");

                try {
                // create JOB
                MethodInvokingJobDetailFactoryBean jobDetail = new MethodInvokingJobDetailFactoryBean();
                jobDetail.setTargetObject(myTask);
                jobDetail.setTargetMethod("performAction");
                jobDetail.setName("MyJobDetail");
                jobDetail.setConcurrent(false);
                jobDetail.afterPropertiesSet();

                /* SimpleTriggerBean trigger = new SimpleTriggerBean();
                trigger.setBeanName("MyTrigger");
                trigger.setJobDetail((JobDetail) jobDetail.getObject());
                trigger.setRepeatInterval(5000);
                trigger.afterPropertiesSet();
                */

                // create CRON Trigger
                CronTriggerBean cronTrigger = new CronTriggerBean();
                cronTrigger.setBeanName("CRON0001");

                // Execute after each 5 second
                String expression = "5 * * * * ?";
                cronTrigger.setCronExpression(expression);
                cronTrigger.afterPropertiesSet();

                //scheduler.scheduleJob(jobDetail, cronTrigger);

                scheduler.scheduleJob((JobDetail) jobDetail.getObject(), cronTrigger);

                // Start Scheduler        
                scheduler.start();

                } catch (Exception e) {                      
                    e.printStackTrace();
                } 
    }
}

Spring 4 me permite hacer esto sin ningún problema (Quartz 2.0) – spring-dispatcher-servlet.xml

<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
<task:scheduler pool-size="10"/>
<task:executor pool-size="1"/>

Inyecte el bean creado anteriormente en Spring bean o Service Class

@Service
public class DynamicJobExample {

@Autowired
@Qualifier("myScheduler")
private TaskScheduler scheduler;

public void schedule() throws ParseException {
    scheduler.schedule(new MyTask(), new CronTrigger("5 * * * * ?"));
  }
}

MyTask debe ser una clase ejecutable

public class MyTask implements Runnable{

@Override
public void run() {
    System.out.println("Hey, you reached me...:)");
  }
}

Las dependencias de Maven son (pom.xml)

<spring.version>4.1.0.RELEASE</spring.version>

   <dependency>
        <groupId>org.quartz-scheduler</groupId>
        <artifactId>quartz</artifactId>
        <version>2.2.1</version>
    </dependency>
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *