SpringBoot整合Quartz

SpringBoot整合Quartz

依赖:

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>

Job:

@Component
public class MyFirstJob {
    public void sayHello() {
        System.out.println("MyFirstJob: hello!");
    }
}

public class MySecondJob extends QuartzJobBean {

    private String name;

    public void setName(String name) {
        this.name = name;
    }

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("MySecondJob:hello " + name + ":" + new Date());
    }
}

Job可以是一个普通的JavaBean,如果是普通的JavaBean,那么可以先添加@Component注解注册到容器。Job也可以继承抽象类QuartzJobBean,若继承自QuartzJobBean,则需要实现该类中的executeInternal方法,该方法在任务被调用时使用。

config:

@Configuration
public class QuartzConfig {

    @Bean
    public MethodInvokingJobDetailFactoryBean jobDetail() {
        MethodInvokingJobDetailFactoryBean bean = new MethodInvokingJobDetailFactoryBean();
        bean.setTargetBeanName("myFirstJob");
        bean.setTargetMethod("sayHello");
        bean.setName("job1");
        bean.setGroup("group");
        return bean;
    }

    @Bean
    public JobDetailFactoryBean jobDetail2() {
        JobDetailFactoryBean bean = new JobDetailFactoryBean();
        bean.setJobClass(MySecondJob.class);
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("name", "test");
        bean.setJobDataMap(jobDataMap);
        bean.setDurability(true);
        bean.setName("job2");
        bean.setGroup("group");
        return bean;
    }

    @Bean
    public SimpleTriggerFactoryBean simpleTriggerFactoryBean() {
        SimpleTriggerFactoryBean bean = new SimpleTriggerFactoryBean();
        bean.setJobDetail(jobDetail().getObject());//关联job
        bean.setRepeatCount(3);//实际执行4次
        bean.setStartDelay(1000);
        bean.setRepeatInterval(2000);
        bean.setName("trigger1");
        bean.setGroup("group");
        return bean;
    }

    @Bean
    public CronTriggerFactoryBean cronTriggerFactoryBean() {
        CronTriggerFactoryBean bean = new CronTriggerFactoryBean();
        bean.setJobDetail(jobDetail2().getObject());//关联job
        bean.setCronExpression("0/2 * * * * ?");
        bean.setName("trigger2");
        bean.setGroup("group");
        return bean;
    }


    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        bean.setTriggers(simpleTriggerFactoryBean().getObject(), cronTriggerFactoryBean().getObject());
        return bean;
    }
}

启动:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值