1. 程式人生 > >spring4 ssm整合quartz,單定時任務

spring4 ssm整合quartz,單定時任務

這種配置方式,只適合在專案新增後臺定時任務。

1.新增maven依賴

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

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

2.增加定時任務配置到spring-context.xml

	 <!-- 定時任務實現類 -->
	<bean name="jobClass" class="TimerTask"/>

    <bean id="increJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject">
            <ref bean="jobClass"/>
        </property>
        
        <property name="targetMethod">  
       		 <!-- 要執行的方法名稱 -->
            <value>execute</value>
        </property>
    </bean>

    <!-- ======================== 排程觸發器 ======================== -->
    <bean id="cronTriggerBean" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="increJob"></property>
 		<!-- 每3秒執行一次 -->
        <property name="cronExpression" value="0/3 * * * * ?"></property>
    </bean>

    <!-- ======================== 排程工廠(此種方法可以使用註解方式呼叫Service、Dao)======================== -->
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <!-- 以註解方式引用 JobFactory類 -->
        <property name="jobFactory" ref="jobFactory" />
        <property name="triggers">
            <list>
                <ref bean="cronTriggerBean" />
            </list>
        </property>
    </bean>

JobFactory類

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;
import org.springframework.stereotype.Service;

@Service("jobFactory")
public class JobFactory extends AdaptableJobFactory {
    @Autowired
    private AutowireCapableBeanFactory autowireCapableBeanFactory;

    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        Object  jobInstance=  super.createJobInstance(bundle);
        autowireCapableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
}

TimerTask類

import javax.annotation.Resource;
import java.util.List;

public class TimerTask {
    @Resource
    PersonService personService;
    public void execute() {
        List<Persion> all = personService.getAll();
        System.out.println(all);
    }
}

將專案部署到伺服器,啟動就會執行。