java 善假于物(三):quartz 定时器融合 spring「终于解决」

Java (65) 2023-08-12 21:12

Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说java 善假于物(三):quartz 定时器融合 spring「终于解决」,希望能够帮助你!!!。

前言

在spring的项目开发中,我们经常会用到定时器,虽然java本身提供了定时器,但是我为大家推荐一个更强的的作业调度框架:quartz,接下来教大家怎么利用spring全程注解的方式配置quartz

1.maven配置



 org.quartz-scheduler quartz 2.2.3 

2.spring的注解配置文件QuartzConfiguration.java

package com.qingcheng.club.configuration;

import com.qingcheng.club.quartz.LoseClassQuartz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

@Configuration
public class QuartzConfiguration {

    @Autowired
    private LoseClassQuartz loseClassQuartz;

    @Bean
    public MethodInvokingJobDetailFactoryBean jobDetail(){
        MethodInvokingJobDetailFactoryBean methodInvokingJobDetailFactoryBean = new MethodInvokingJobDetailFactoryBean();
        methodInvokingJobDetailFactoryBean.setTargetObject(loseClassQuartz);
        methodInvokingJobDetailFactoryBean.setTargetMethod("doJob");
        return methodInvokingJobDetailFactoryBean;
    }

    @Bean
    public CronTriggerFactoryBean cronTriggerBean(){
        CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
        cronTriggerFactoryBean.setJobDetail(jobDetail().getObject());
        //每5秒执行一次
        //cronTriggerFactoryBean.setCronExpression("0/5 * * * * ?");
        //每秒执行一次,这个表达式很重要,任务调度执行频率
        cronTriggerFactoryBean.setCronExpression("* * * * * ?");
        return cronTriggerFactoryBean;
    }

    @Bean
    public SchedulerFactoryBean trigger(){
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setTriggers(cronTriggerBean().getObject());
        return schedulerFactoryBean;
    }
}

3.测试任务LoseClassQuartz.java

package com.qingcheng.club.quartz;

import com.qingcheng.service.BookService;
import com.qingcheng.util.Globals;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Component("LoseClassQuartz")
public class LoseClassQuartz{

    private static Logger logger = LoggerFactory.getLogger(LoseClassQuartz.class);

    public void doJob(){
        SimpleDateFormat sdfyyyyMMddHHmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String now = sdfyyyyMMddHHmmss.format(new Date());
        System.out.println("time:"+now);
    }
}

4.运行结果:

java 善假于物(三):quartz 定时器融合 spring「终于解决」_https://bianchenghao6.com/blog_Java_第1张

运行成功!

github地址:github.com/bigbeef
个人博客:www.cppba.com

今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

发表回复