How to utilize Quartz in Spring?
To use Quartz in Spring, follow these steps:
- support for the Spring framework’s context
- one option could be
– “quartz crystal”
- Work
- Job interface provided by the org.quartz package
- carry out
- Details of the job
- Initiate
- This is a FactoryBean for creating Schedulers.
- FactoryBean for job details
- Injects the dependency
- Calendar manager
- Appointment organizer
- The scheduler will set up a job to be executed according to the specified trigger.
The sample code is shown below:
- Create a Job class.
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!");
}
}
- Set up the JobDetail and Trigger.
<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>
- Configure the Scheduler and its related Beans.
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="myTrigger" />
</list>
</property>
</bean>
- Utilize Scheduler
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();
}
}
}
In this way, you can use Quartz for task scheduling in Spring.