Java定时任务Quartz

第一步:pom文件中添加依赖包

第二步:创建xml文件,名称为:spring-scheduler 路径如下图:

第三步:spring-scheduler配置详情

<!--创建任务-->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="jobDetails">
            <list>
                <ref bean="updateTimeOutUrgentJobDetail" />
                <ref bean="earlyWarnJobDetail" />
                <!--<ref bean="msgPushJobDetail" />-->
            </list>
        </property>
<!--引入触发器-->
        <property name="triggers">
            <list>
                <ref bean="updateTimeOutUrgentTrigger" />
                <ref bean="earlyWarnJobTrigger" />
                <!--<ref bean="msgPushJobTrigger" />-->
            </list>
        </property>
    </bean>

    <!--任务 引入具体的service-->
    <bean id="updateTimeOutUrgentJobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <property name="jobClass" value="cn.com.klec.bepcs.web.quartz.TimeOutUrgentJob" />
        <property name="jobDataMap">
            <map>
                <entry key="timeOutUrgentJobService" value-ref="timeOutUrgentJobService" />
            </map>
        </property>

        <property name="durability" value="true" />
    </bean>
<!--创建触发器-->
     <bean id="updateTimeOutUrgentTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<!--引入任务-->
        <property name="jobDetail" ref="updateTimeOutUrgentJobDetail" />
<!--指定 Cron 表达式-->
        <property name="cronExpression" value="0 0 * * * ?"/>
    </bean>

第三步:实现定时任务,具体的业务操作

第四步:创建任务 TimeOutUrgentJob

public class TimeOutUrgentJob extends QuartzJobBean {
    private static final Logger LOG = LoggerFactory.getLogger(TimeOutUrgentJob.class);
    private TimeOutUrgentJobService timeOutUrgentJobService;
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        LOG.info("**********************里程碑催办任务启动*******************************");
        try {
            timeOutUrgentJobService = (TimeOutUrgentJobService) context.getMergedJobDataMap().get("timeOutUrgentJobService");
             timeOutUrgentJobService.insertInfo();
            
            
        } catch (Exception e) {
            LOG.error("里程碑催办任务异常: ", e);
        } finally {
            LOG.info("**************************里程碑催办任务结束 **************************");
        }
    }
        
}

第五步:启动项目

注释:timeOutUrgentJobService.insertInfo();就是项目中需要具体实现的业务,quartz默认10个线程

原文地址:https://www.cnblogs.com/dslnn/p/10329467.html