(办公)定时任务quartz入门

  1.简单入门.

       2.定时任务注入service.

          入门案例:

         1.1. 加jar

<dependency>
   <groupId>org.quartz-scheduler</groupId>
   <artifactId>quartz</artifactId>
   <version>2.2.3</version>
</dependency>

        1.2.编写个job任务.

  

/**
 * Quartz中的job可以理解为一个任务.
 */
public class HelloJob implements Job {


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //打印当前的时间:
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("Job Run Time:" + sf.format(date));
        //编写具体的业务逻辑.
        System.out.println("Hello Word!");
    }
}

   1.3  写一个main方法调用任务:

public static void main(String[] args){
    //1.创建一个JobDetail实例,将该实例与HelloJob Class绑定.

    JobDetail jobDetail = JobBuilder.newJob(HelloJob.class)
            .withIdentity("myjob", "group1").build();
    //withIdentity 创建名字,以什么组入伙,build()创建.

    //2.创建Trigger实例,主要用来,定义job执行.
    //每隔2秒重复执行一次,
    // 解释:因为不同类,所以并不是同一个组的.
    // startNow 立即执行.
    // repeatForever 不间断.
    // withIntervalInSeconds 时间间隔秒,执行.
    Trigger trigger = TriggerBuilder.newTrigger()
            .withIdentity("mytrigger","group1")
            .startNow().withSchedule(
                    SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever()
            ).build();

    // 3.创建scheduler 实例:
    SchedulerFactory sfactory = new StdSchedulerFactory();
    try {
        Scheduler scheduler = sfactory.getScheduler();
        scheduler.start();//执行.
        scheduler.scheduleJob(jobDetail,trigger);//绑定要执行的任务.
    } catch (SchedulerException e) {
        e.printStackTrace();
    }


}

    接下来,再来一个简单的springmvc与quartz的结合.

    

1.第一步,加入核心的jar.
spring上下文.
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-aop</artifactId>
   <version>${spring.version}</version>
</dependency>
spring事务:
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-tx</artifactId>
   <version>${spring.version}</version>
</dependency>
定时任务:
<dependency>
   <groupId>org.quartz-scheduler</groupId>
   <artifactId>quartz</artifactId>
   <version>2.2.3</version>
</dependency>
2.Quartz配置作业:
2.1. AnotherBean类
import org.springframework.stereotype.Component;

@Component("anotherBean")
public class AnotherBean {
    public void printAnotherMessage() {
        System.out.println("AnotherMessage");
    }
}
2.2.FirstScheduledJob类
import java.text.SimpleDateFormat;
import java.util.Date;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class FirstScheduledJob extends QuartzJobBean{
     private AnotherBean anotherBean;
     
     public void setAnotherBean(AnotherBean anotherBean){
         this.anotherBean = anotherBean;
     }

    @Override
    protected void executeInternal(JobExecutionContext arg0)
            throws JobExecutionException {
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("10 :FirstScheduledJob Executes!" + sf.format(date));
        this.anotherBean.printAnotherMessage();        
    }
}
2.3.MyBean
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.stereotype.Component;

@Component("myBean")
public class MyBean {
    public void printMessage() {
        // 打印当前的执行时间,格式为2017-01-01 00:00:00
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("MyBean Executes!" + sf.format(date));
    }
}
2.4.配置文件里配置一下:
<bean id="simpleJobDetail"
        class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="myBean" />
        <property name="targetMethod" value="printMessage" />
    </bean>

    <bean id="firstComplexJobDetail"
        class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <property name="jobClass"
            value="com.imooc.springquartz.quartz.FirstScheduledJob" />
        <property name="jobDataMap">
            <map>
                <entry key="anotherBean" value-ref="anotherBean" />
            </map>
        </property>
        <property name="Durability" value="true"/>                
    </bean>
    <!-- 距离当前时间1秒之后执行,之后每隔两秒钟执行一次 -->
    <bean id="mySimpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
        <property name="jobDetail"  ref="simpleJobDetail"/>
        <property name="startDelay"  value="1000"/>
        <property name="repeatInterval"  value="2000"/>
    </bean>
    
    <!-- 每隔5秒钟执行一次 -->
    <bean id="myCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail"  ref="firstComplexJobDetail"/>
        <property name="cronExpression"  value="0 0/3 * * * ? *"/>
    </bean>
    
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">


        <property name="jobDetails">
            <list>
                <ref bean="simpleJobDetail"/>
                <ref bean="firstComplexJobDetail"/>
            </list>
        </property>
        <property name="triggers">
            <list>
                <!--
                <ref bean="mySimpleTrigger"/>
                -->
                <ref bean="myCronTrigger"/>
            </list>
        </property>
    </bean>

    2.1 定时任务注入service,注入service,为null?

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;

public class MyJobFactory  extends AdaptableJobFactory {

    //这个对象Spring会帮我们自动注入进来,也属于Spring技术范畴.
    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;

    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        //调用父类的方法
        Object jobInstance = super.createJobInstance(bundle);
        //进行注入,这属于Spring的技术,不清楚的可以查看Spring的API.
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
}
放到bean里
<bean id="jobFactory" class="cn.wz.ssm.quartz.MyJobFactory"></bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="jobFactory" ref="jobFactory"></property>

      然后注入的service就可以使用了。

           分享一个:http://cron.qqe2.com/ 写定时任务表达式的网址。

      本篇文章,通过东拼西凑,瞎划拉资料,不过东西测试过了,可以使用.

       

    

    

  

posted on 2019-05-08 17:46  六一儿童节  阅读(401)  评论(0编辑  收藏  举报

导航