spring quartz 的调度任务

quartz的调度任务比jdk原生的定时任务功能强大的多,可以使用cron的表达式定义任务的调度时间,而jdk的

timer定时器则做不到这点。下面使用spring的xml配置静态的调度任务

//自定义的job

public class StatisticJob
{
     public void statistic()
     {

        //业务逻辑编写
         System.out.println(new Date());
     }
}



<!-- quartz定时任务调度 -->
    <bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" >
         <property name="triggers">
            <list>
               <ref bean="cronTrigger"/>
            </list>
         </property>   
    </bean>
    <bean id="statisticJob" class="com.westone.quartz.StatisticJob"></bean>
    <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetBeanName" value="statisticJob"></property>
        <property name="targetMethod" value="statistic"></property>
    </bean>
    <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
      <property name="jobDetail" ref="jobDetail"></property>
      <property name="cronExpression" value="0/5 * * * * ?"></property>
    </bean>



测试代码

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath*:config/spring/root-context.xml")
@TestExecutionListeners( { DependencyInjectionTestExecutionListener.class, TransactionalTestExecutionListener.class })
public class SpringStartTest
{

@Test
    public void test() throws InterruptedException
    {
        while(true)
        {
            Thread.sleep(1000);
        }
        
    }
}

使用junit测试时发现控制台 每隔5秒输出时间    代码任务已经调度执行。

猜你喜欢

转载自blog.csdn.net/ld2007081055/article/details/37561371