在Spring中使用Quartz,可以按照以下步骤进行:
spring-context-support
和quartz
.Job
实现类,实现org.quartz.Job
接口,并实现execute
方法,该方法中定义具体的任务逻辑。JobDetail
,用于定义Job的属性,例如Job名称、所属组等。Trigger
,用于定义触发Job的条件,例如触发时间表达式。SchedulerFactoryBean
和JobDetailFactoryBean
。@Autowired
注解注入Scheduler
实例。Scheduler
的方法,例如scheduler.scheduleJob(jobDetail, trigger)
来调度Job。示例代码如下:
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class MyJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
// 任务逻辑
System.out.println("Hello, Quartz!");
}
}
<bean id="myJobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.example.MyJob" />
<property name="jobDataAsMap">
<map>
<!-- 可以添加一些自定义的参数 -->
<entry key="param1" value="value1" />
</map>
</property>
</bean>
<bean id="myTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="myJobDetail" />
<property name="cronExpression" value="0/5 * * * * ?" />
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="myTrigger" />
</list>
</property>
</bean>
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
public class MyScheduler {
@Autowired
private Scheduler scheduler;
public void start() {
try {
scheduler.start();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
这样就可以使用Quartz在Spring中进行任务调度了。