一、java定时任务可以通过Timer、TimerTask配合完成。可以参考详解java定时任务
二、通过quartz实现定时任务
方法一:
<!-- 使用MethodInvokingJobDetailFactoryBean,任务类可以不实现Job接口,通过targetMethod指定调用方法-->
<bean id="startTaskWorks" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="object" ref="testObject" />
<property name="method" ref="testMethod" />
<property name="concurrent" value="false" />
</bean>
<!-- 调度触发器 -->
<bean id="startWorkTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="startTaskWorks" />
<!-- cron表达式 -->
<property name="cronExpression" value="5 * * * * ?" />
</bean>
<!-- 调度工厂 -->
<bean id="schedulerFactory" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="Triggers">
<list bean="startWorkTrigger" />
</property>
</bean>
<bean id="object" class="com.client.testObject">
<property name="object1" ref="objcet1" />
<property name="object2" ref="objcet2" />
</bean>
<bean id="object1" class="com.client.object1" />
<bean id="object2" class="com.client.object2" />
方法二:
<context:component-scan base-package="com.email" />
<!-- For times when you need more complex processing, passing data to the
scheduled job -->
<bean name="complexJobDetail"
class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass"
value="com.email.job.ParseEmlScheduledJob" />
<property name="durability" value="true" />
<property name="name" value="ParseEmlScheduledJob" />
<property name="group" value="myGroup" />
</bean>
<!-- Run the job every 2 seconds with initial delay of 1 second -->
<bean id="simpleTrigger"
class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
<property name="jobDetail" ref="complexJobDetail" />
<property name="startDelay" value="1000" />
<property name="repeatInterval" value="10000" />
</bean>
<!-- Scheduler factory bean to glue together jobDetails and triggers to
Configure Quartz Scheduler -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="jobDetails">
<list>
<ref bean="complexJobDetail" />
</list>
</property>
<property name="triggers">
<list>
<ref bean="simpleTrigger" />
</list>
</property>
<property name="quartzProperties">
<props>
<prop key="org.quartz.jobStore.class">org.quartz.simpl.RAMJobStore</prop>
</props>
</property>
</bean>
//要调用的任务需要extends QuartzJobBean
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Deprecated
public class ParseEmlScheduledJob extends QuartzJobBean {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Override
protected void executeInternal(JobExecutionContext context) {
ParseEml.parserEml();
}
}
reference:
详解java定时任务
Spring 3整合Quartz 2实现定时任务一:常规整合