分布式任务调度框架Quartz

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ldj.quartz</groupId>
    <artifactId>quartz</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.12.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz-jobs</artifactId>
            <version>2.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
package com.ldj.quartz.job;

import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * User: ldj
 * Date: 2024/4/9
 * Time: 17:38
 * Description: 数据同步任务
 */
@Slf4j
public class HelloJob implements Job {

    /**
     * @param jobExecutionContext 能获取到job的详细数据和Quartz运行时环境信息
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Date date = new Date();
        String formatDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date);
        log.info("[{}] 读取任务表...",formatDate);
        doSth(2);
        log.info("[{}] 校验任务...",formatDate);
        log.info("[{}] 校验任务通过...",formatDate);
        doSth(1);
        log.info("[{}] 执行数据同步...", formatDate);
        doSth(2);
        log.info("[{}] 数据同步成功...", formatDate);

        JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        System.out.println(jobDataMap.get("username"));
    }

    private static void doSth(int time){
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
package com.ldj.quartz.demo;

import com.ldj.quartz.constant.JobConstant;
import com.ldj.quartz.job.HelloJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

/**
 * User: ldj
 * Date: 2024/4/9
 * Time: 18:02
 * Description: No Description
 */
public class HelloScheduler {

    public static void main(String[] args) throws Exception {
        //任务调度器
        Scheduler stdScheduler = StdSchedulerFactory.getDefaultScheduler();

        //构建任务详情
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("username", "ldj009");
        jobDataMap.put("password", "drs94!");

        JobDetail jobDetail = JobBuilder.newJob(HelloJob.class)
                .withIdentity(JobConstant.JOB_NAME_01, JobConstant.JOB_SYNC_DATA)
                .usingJobData(jobDataMap)
                .build();

        //任务触发规则
        SimpleTrigger trigger1 = TriggerBuilder.newTrigger()
                .withIdentity(JobConstant.TRIGGER_NAME_01, JobConstant.TRIGGER_SYNC_DATA)
                .startNow()
                //间隔15秒执行
                .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(15))
                .build();

       CronTrigger trigger2 = TriggerBuilder.newTrigger()
                .withIdentity(JobConstant.TRIGGER_NAME_01, JobConstant.TRIGGER_SYNC_DATA)
                .startNow()
                //cron表达式
                .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
                .build();

        //执行调度
        stdScheduler.scheduleJob(jobDetail, trigger1);
        stdScheduler.start();
    }

}

监听器(类似aop编程) 

package com.ldj.quartz.listener;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;

/**
 * User: ldj
 * Date: 2024/4/10
 * Time: 17:13
 * Description: job监听器
 */
public class HelloJobListener implements JobListener {

    //获取监听器名称
    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    //job被执行之前触发
    @Override
    public void jobToBeExecuted(JobExecutionContext jobExecutionContext) {
        System.out.println("---------job被执行之前触发-----------");
    }

    //被Trigger否决时触发
    @Override
    public void jobExecutionVetoed(JobExecutionContext jobExecutionContext) {
        System.out.println("---------被Trigger否决时触发-----------");
    }

    //job被执行之后触发
    @Override
    public void jobWasExecuted(JobExecutionContext jobExecutionContext, JobExecutionException e) {
        System.out.println("---------job被执行之后触发发-----------");
    }

}
package com.ldj.quartz.demo;

import com.ldj.quartz.constant.JobConstant;
import com.ldj.quartz.job.HelloJob;
import com.ldj.quartz.listener.HelloJobListener;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.EverythingMatcher;
import org.quartz.impl.matchers.KeyMatcher;

/**
 * User: ldj
 * Date: 2024/4/10
 * Time: 17:15
 * Description: No Description
 */
public class HelloJobListenerTest {

    public static void main(String[] args) throws Exception {
        //任务调度器
        Scheduler stdScheduler = StdSchedulerFactory.getDefaultScheduler();

        JobDetail jobDetail = JobBuilder.newJob(HelloJob.class)
                .withIdentity(JobConstant.JOB_NAME_01, JobConstant.JOB_SYNC_DATA)
                .build();

        //任务触发规则
        SimpleTrigger trigger1 = TriggerBuilder.newTrigger()
                .withIdentity(JobConstant.TRIGGER_NAME_01, JobConstant.TRIGGER_SYNC_DATA)
                .startNow()
                //间隔5秒执行
                .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(15))
                .build();

        stdScheduler.scheduleJob(jobDetail, trigger1);

        //1.创建全局监听器 (不常用)
        //stdScheduler.getListenerManager().addJobListener(new HelloJobListener(), EverythingMatcher.allJobs());
        //2.创建局部监听器 (指定任务执行)
        JobKey jobKey = JobKey.jobKey(JobConstant.JOB_NAME_01, JobConstant.JOB_SYNC_DATA);
        stdScheduler.getListenerManager().addJobListener(new HelloJobListener(), KeyMatcher.keyEquals(jobKey));
        stdScheduler.start();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值