• 定时任务:SpringBoot+Quartz



    Quartz说明

    定时任务主要使用它的三大组件。

    • 调度器:Scheduler。
    • 任务:JobDetail。
    • 触发器:Trigger,包括 SimpleTrigger 和 CronTrigger。

    使用流程:

    1. 创建任务:具体的业务逻辑,需要实现Job接口,将业务逻辑代码存放在void execute(JobExecutionContext context) 方法中。
    2. 定时执行任务:将任务创建好后,定时执行它,需要用到Quartz的三大组件:
    • JobDetail用来绑定Job,并设置任务的相关属性
    • Trigger指定Job的执行时间,执行间隔,运行次数等
    • Schedule来负责调度结合JobDetail和Trigger

    实战演练

    在这里插入图片描述

    1. pom.xml 导入相关依赖【springboot和Quartz】
        <dependencies>
    
            
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webartifactId>
                <version>2.5.1version>
            dependency>
    
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-testartifactId>
                <version>2.5.1version>
            dependency>
    
            
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-quartzartifactId>
                <version>2.5.1version>
            dependency>
        dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    1. application.yml 【不需要配置】
    2. QuartzApplication启动类
    @SpringBootApplication
    public class QuartzApplication {
        public static void main(String[] args) {
            SpringApplication.run(QuartzApplication.class, args);
            System.out.println("QuartzApplication启动成功");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    1. 任务:DemoJob【需要定时开启的任务】
    /**
     * 

    DemoJob

    *

    定时任务

    * * @author : he zhe * @date : 2022-07-29 14:26 **/
    public class DemoJob implements Job { @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { //获取JobDetail中传递的参数 String url = (String) jobExecutionContext.getJobDetail().getJobDataMap().get("url"); //获取当前时间 Date date = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //打印信息 System.out.println("当前时间:" + dateFormat.format(date)+" 用户:"+new Random().nextInt(100)+" 访问了"+url); System.out.println("----------------------------------------"); } }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    1. 工具类:JobUtils【开启和关闭定时任务方法封装】
    /**
     * 

    JobUtils

    *

    任务调度工具类

    * * @author : he zhe * @date : 2022-07-29 14:49 **/
    public class JobUtils { private static SchedulerFactory schedulerFactory; private static void setSchedulerFactory(){ schedulerFactory = new StdSchedulerFactory(); } public static void open(String className, String jobId){ if (schedulerFactory == null) { setSchedulerFactory(); } try { // 1、创建调度器Scheduler Scheduler scheduler = schedulerFactory.getScheduler(); // 2、创建JobDetail实例,并与Job类绑定(Job执行内容) className = "com.study.job."+className; Class forName = Class.forName(className); JobDetail jobDetail = JobBuilder.newJob(forName) .withIdentity(jobId) .usingJobData("url","https://blog.csdn.net/qq_43466788") .build(); // 3、构建Trigger实例,每隔1s执行一次 Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "triggerGroup1") .startNow()//立即生效 .withSchedule(SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(1)//每隔1s执行一次 .repeatForever()).build();//一直执行 //4、执行 scheduler.scheduleJob(jobDetail, trigger); System.out.println("--------scheduler start ! ------------"); scheduler.start(); } catch (Exception e) { e.printStackTrace(); } } public static void close(String jobId) { try { // 任务全部使用同一个调度器 Scheduler scheduler = null; // 获取调度器 scheduler = schedulerFactory.getScheduler(); JobKey jobKey = JobKey.jobKey(jobId); // 添加到调度器 scheduler.deleteJob(jobKey); System.out.println("--------scheduler shutdown ! ------------"); } catch (Exception e) { e.printStackTrace(); } } }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    1. 接口:DemoJobController【控制定时任务开启关闭】
    @RestController
    public class DemoJobController {
    
        @RequestMapping(value = "/open", method = RequestMethod.POST)
        public String test(String className) {
            //开启定时任务
            JobUtils.open(className,"1");
            return "定时任务启动成功";
        }
    
        @RequestMapping(value = "/close", method = RequestMethod.POST)
        public String test2(String jobId) {
            //开启定时任务
            JobUtils.close(jobId);
            return "定时任务关闭成功";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    1. 启动服务
      访问:http://localhost:80/open?className=DemoJob
      在这里插入图片描述
      然后就可以在控制台看到:【不停的打印】
      在这里插入图片描述
      访问:POST http://localhost:80/close?jobId=1
      在这里插入图片描述
      控制台打印scheduler shutdown !后,停止了定时任务
      在这里插入图片描述

  • 相关阅读:
    k8s yaml文件含义
    力扣108. 将有序数组转换为二叉搜索树
    Angular distance
    若依框架解读(微服务版)—— 4.认证,登出(Gateway网关)
    为什么HttpContextAccessor要这么设计?
    作为可信基础设施,区块链为“双碳”带来了什么? | 研讨会回顾
    弘辽科技:淘宝旧链接如何打新品标?有什么规则?
    LeetCode刷题---707. 设计链表(双向链表-带头尾双结点)
    React中的useCallback和useMemo
    Vue $nextTick
  • 原文地址:https://blog.csdn.net/qq_43466788/article/details/126054679