浅谈java定时任务:quartz、quartz with spring

本文讲一下quartz、quartz with spring

  • 添加依赖:
 <dependency>
            <groupId>org.quartz-schedulergroupId>
            <artifactId>quartzartifactId>
            <version>1.8.5version>
 dependency>

quartz

  • 注册job
public class InvokeQuartz {
    public void start() {
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        try {
            Scheduler scheduler = schedulerFactory.getScheduler();
            JobDetail jobDetail = new JobDetail("quartzJob", MyJob.class);
            CronTrigger cronTrigger = new CronTrigger("quartzTrigger");

            CronExpression cronExpression = new CronExpression("* * * * * ?");
            cronTrigger.setCronExpression(cronExpression);
            scheduler.scheduleJob(jobDetail,cronTrigger);
            scheduler.start();

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

    }
}
  • 实现job
public class MyJob implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("quartz 任务开始-----------");
    }
}
  • 初始化定时任务
"invokeQuartz" class="com.task.InvokeQuartz" init-method="start"/>

quartz with spring

quartz with spring 将 配置信息全部交给spring 使用者只需要专心实现定时任务主要逻辑即可

  • xml 配置

      
    <bean id="SpringJobSchedulerFactoryBean"
         class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="taskTrigger"/>
            list>
        property>
    bean>
     
    <bean id="taskTrigger"
          class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail">
            <ref bean="myJobDetail" />
        property>
        <property name="cronExpression">
        //cron 表达式(在另一篇文章里有详细介绍)
            <value>0/20 * * * * ?value>
        property>
    bean>
    
    <bean id="myJob" class="com.task.MyJob"/>
    
    <bean id="myJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="myJob"/>
        <property name="targetMethod" value="execute"/>
        <property name="concurrent" value="false" />
    bean>
  • MyJob 实现

public class MyJob{
    public void execute() {
        System.out.println("定时任务开始");
    }
}

你可能感兴趣的:(java)