一、xml配置的方式,主要分为两步:
1、继承QuartzJobBean接口,实现其executeInternal()方法,代码如下:
package com.cncbi.riw.batch.job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
/*
* 实现QuartzJobBean的executeInternal方法
*/
//@Component
public class TestJob extends QuartzJobBean {
private static Logger logger = LoggerFactory.getLogger(TestJob.class);
@Override
public synchronized void executeInternal(JobExecutionContext context) throws JobExecutionException {
// TODO Auto-generated method stub
logger.info("-----------------------------------------testjob2------------------------------");
logger.info("-----------------------------------------testjob2------------------------------");
logger.info("-----------------------------------------testjob2------------------------------");
logger.info("-----------------------------------------testjob2------------------------------");
logger.info("-----------------------------------------testjob2------------------------------");
}
}
2、完成xml配置
<bean id="testJob"
class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass">
<value>com.cncbi.riw.batch.job.TestJob</value>
</property>
<property name="jobDataAsMap">
<map>
<entry key="wareHouseService">
<ref bean="wareHouseService" />
</entry>
</map>
</property>
</bean>
<bean id="testTrigger"
class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
<property name="jobDetail">
<ref bean="testJob" />
</property>
<property name="startDelay">
<value>15000</value>
</property>
<property name="repeatInterval">
<value>1500000</value>
</property>
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="testTrigger" />
</list>
</property>
</bean>
二、注解的方式
直接在方法上加上以下注解,通过cron表达式定时启动
@Scheduled(cron = "${spider.interbank.cron}")
三、代码的方式
主要分为4步:
//1、定义定时调用工厂对象 并启动
StdSchedulerFactory factory = new StdSchedulerFactory();
Scheduler scheduler = factory.getScheduler();
//调度器实例启动
scheduler.start();
//2、构造触发器 设置触发条件
Trigger trigger = new CronTrigger();
//设置起始时间为当前时间
trigger.setStartTime(new Date());
//设置调用时间表达式(*秒 *分 *时 *日 *月 *年)
((CronTrigger) trigger).setCronExpression(express);
//3、jobDetail实例构造
JobDetail jobDetail = new JobDetail();
// 设置BeanName属性
jobDetail.setName("");
jobDetail.setGroup("");
//***设置调度器的class
jobDetail.setJobClass(Class.forName(autoScheduleSetVO.getClassName()));
jobDetail.getJobDataMap().put("autoScheduleSetVO", autoScheduleSetVO);
//4、调度器启动任务
scheduler.scheduleJob(jobDetail, trigger);