How to utilize Quartz in Spring?

To use Quartz in Spring, follow these steps:

  1. support for the Spring framework’s context
  2. one option could be

    – “quartz crystal”

  3. Work
  4. Job interface provided by the org.quartz package
  5. carry out
  6. Details of the job
  7. Initiate
  8. This is a FactoryBean for creating Schedulers.
  9. FactoryBean for job details
  10. Injects the dependency
  11. Calendar manager
  12. Appointment organizer
  13. The scheduler will set up a job to be executed according to the specified trigger.

The sample code is shown below:

  1. 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!");
    }
}
  1. 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>
  1. Configure the Scheduler and its related Beans.
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="triggers">
        <list>
            <ref bean="myTrigger" />
        </list>
    </property>
</bean>
  1. 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.

bannerAds