定时器quartz结合spring使用

时间:2021-09-28 23:36:03

1.quartz版本:1.x建议使用quartz-all-1.8.6.jar;

2.spring版本:2.x,3.x及以上quartz版本需要使用2.x的quartz;

3.配置:

<!--指定时间运行 
1.秒(0–59 - * /)
2.分钟(0–59 - * / )
3.小时(0–23 - * / )
4.月份中的日期(1–31 - * ? / L W C )
5.月份(1–12或JAN–DEC - * / )
6.星期中的日期(1–7或SUN–SAT - * ? / L C #)
7.年份(1970–2099 empty, 1970-2099 , - * /)
-->

<bean name="onekey" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="com.xxx.OnekeyAutoThreadBean" />
<property name="jobDataAsMap">
<map>
<entry key="timeout" value="0" />
</map>
</property>
</bean>
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="onekey" />

<property name="cronExpression" value="0 0 0,12 * * ?" />
</bean>

<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cronTrigger" />
</list>
</property>
</bean>
任务类:

public class OnekeyAutoThreadBean extends QuartzJobBean {  

private int timeout;
private static int i = 0;
//调度工厂实例化后,经过timeout时间开始执行调度
public void setTimeout(int timeout) {
this.timeout = timeout;
}

/**
* 要调度的具体任务
*/
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
System.out.println("定时任务执行开始…");
...
System.out.println("定时任务执行结束…");
}
}