• Jaca定时任务-01-进程级别的Timer,ScheduledExecutorService,springtask


    1:定时任务比较

    1:定时任务实现的几种方式-进程级别的:

    1、Timer:这是java自带的java.util.Timer类,这个类允许你调度一个java.util.TimerTask任务。使用这种方式可以让你的程序按照某一个频度执行,但不能在指定时间运行。一般用的较少。
    2、ScheduledExecutorService:也jdk自带的一个类;是基于线程池设计的定时任务类,每个调度任务都会分配到线程池中的一个线程去执行,也就是说,任务是并发执行,互不影响。
    3、Spring Task:Spring3.0以后自带的task,可以将它看成一个轻量级的Quartz,而且使用起来比Quartz简单许多。配置简单功能较多,如果系统使用单机的话可以优先考虑spring定时器

    2:定时任务实现的几种方式-支持分布式的:

    4、Quartz:这是一个功能比较强大的的调度器,可以让你的程序在指定时间执行,也可以按照某一个频度执行,配置起来稍显复杂。可支持分布式
    5.elastic-job:当当开发的弹性分布式任务调度系统,功能丰富强大,采用zookeeper实现分布式协调,实现任务高可用以及分片,目前是版本2.15,并且可以支持云开发
    6.xxl-job: 是大众点评员工徐雪里于2015年发布的分布式任务调度平台,是一个轻量级分布式任务调度框架,其核心设计目标是开发迅速、学习简单、轻量级、易扩展。

    2:Timer

    1. 单线程执行,任务可能相互堵塞
    2. 运行时异常会导致timer线程终止
    package com.Timer;
    
    import java.util.Calendar;
    import java.util.Date;
    import java.util.Timer;
    import java.util.TimerTask;
    
    /**
     * @author wkl
     * @create 2022-07-04 9:57
     */
    public class TimerTest {
        public static void main(String[] args) {
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    System.out.println("task  run:" + new Date());
                }
            };
    
            /**
             * 如果指定开始执行的时间在当前系统运行时间之前,scheduleAtFixedRate会把已经过去的时间也作为周期执行,而schedule不会把过去的时间算上。
             */
            //安排指定的任务在指定的时间开始进行重复的固定延迟执行。这里是每3秒执行一次
            Timer timer = new Timer();
            //下次执行任务的时间取决于上次执行完成的时间
            timer.schedule(timerTask, 5000, 3000);
            //
    //        timer.scheduleAtFixedRate(timerTask,10,3000);
        }
    
       
    
        public static void testTimer1() {
            //第一种方法:设定任务 task在指定时间 time执行
            // schedule(TimerTask task,Date time);
            // schedule(TimerTask task, Date time)
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    System.out.println("设定要执行的任务");
                }
            }, 20000);//设定的时间 time,此处为毫秒
        }
    
        public static void testTimer2() {
            //第二种方法:设定指定任务task在指定延迟 delay后,固定频率 period执行
            //schedule(TimerTask task, long delay, long period)
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    System.out.println("我被执行了");
                }
            }, 3000, 3);
        }
    
        public static void testTimer3() {
            //和上边的用法一样,只不过利用calendar日历类,强行做成了根据固定值时间执行
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 12);//控制时
            calendar.set(Calendar.MINUTE, 0);      //控制分
            calendar.set(Calendar.SECOND, 0);      //控制秒
            Date time = calendar.getTime();        // 得出执行任务的时间,此处为今天的12:00:00
            new Timer().scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    System.out.println("-------设定要指定任务--------");
                }
            }, time, 1000 * 60 * 60 * 24);//这里设定将延迟每天固定执行
        }
    }
    
    
    
    • 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
    • 71
    • 72
    • 73

    2:使用ScheduledExecutorService开多线程执行

    1. 使用多线程执行任务,不会相互阻塞
    2. 如果线程失活,会创建新的线程执行任务,抛异常,丢弃异常任务
    package com.Timer.pool;
    
    import java.util.Date;
    import java.util.TimerTask;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.TimeUnit;
    
    /**
     * 用java.util.concurrent.ScheduledExecutorService 来实现定时任务
     * @author wkl
     * @create 2022-07-04 10:16
     */
    public class Scheduled {
        public static void main(String[] args) {
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    System.out.println("task  run:" + new Date());
                }
            };
    
            ScheduledExecutorService service = Executors.newScheduledThreadPool(5);
            //                          执行任务    延迟时间        时间间隔    时间单位
            service.scheduleAtFixedRate(timerTask, 5, 3, TimeUnit.SECONDS);
        }
    
    }
    
    
    • 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

    3:使用Spring Task-Spring 3.0以后自带的task 调度工具

    1:注解使用

    1:任务执行类

    package com.job.SpringTask;
    
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.scheduling.annotation.EnableScheduling;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    import java.util.Date;
    
    /**
     * @author wkl
     * @create 2022-07-04 10:35
     */
    @Component
    @EnableScheduling
    @Async("executor")
    public class SpringTaskTest {
    
        @Scheduled(cron = "*/5 * * * * ?")
        public void test1 (){
            System.out.println("每5秒执行一次:"+new Date());
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    2:线程池配置类

    package com.job.SpringTask;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.scheduling.annotation.EnableAsync;
    import org.springframework.scheduling.annotation.EnableScheduling;
    import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
    
    import java.util.concurrent.Executor;
    
    /**
     * springtask设置类,设置springtask任务线程池
     *
     * @author wkl
     * @create 2022-07-04 10:56
     */
    @Configuration
    @EnableAsync
    public class AsycConfig {
        /*
       此处成员变量应该使用@Value从配置中读取
        */
        private int corePoolSize = 10;
        private int maxPoolSize = 200;
        private int queueCapacity = 10;
    
        @Bean
        public Executor taskExecutor() {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(corePoolSize);
            executor.setMaxPoolSize(maxPoolSize);
            executor.setQueueCapacity(queueCapacity);
            executor.initialize();
            return executor;
        }
    }
    
    
    • 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

    3:参数说明

    使用@Async开启异步模式,@Async的值为执行器executor,名字需要与xml中配置的一致。
    executor用于配置线程池
    pool-size:线程池数量,可以设置范围,也可以设置指定值,最小值为1,最大值为Integer.MAX_VALUE。
    queue-capacity:任务队列,当线程数达到最小值时,新任务将会被放到队列中。当队列被占满时,executor就会在线程池中创建新的线程,执行新的任务。
    keep-alive:pool-size的最小值是指核心线程的数量,超过这个数的其他线程,当执行完任务后,可以存活keep-alive指定的时间,单位毫秒。
    rejection-policy:当线程数达到最大值时,系统的处理策略,可以设置4种方式:
    ABOAT:默认值,抛出异常,不再执行新的任务,直到有空闲线程可以使用
    DISCARD:不抛出异常,不再执行新的任务,知道有空闲线程可以使用
    CALLER_RUNS:在当前线程中执行新的任务
    DISCARD_OLDEST:丢弃最旧的一个任务,空出线程执行新的任务

    2:xml配置使用

    1:任务执行类

    package com.sawyer.job;
    import java.util.Date;
    
    public class TaskTest {
        public void run() {
            System.out.println(new Date() + " and current thread is " + Thread.currentThread().getName());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2:在xml中声明bean

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:task="http://www.springframework.org/schema/task"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
           http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
    
        <!-- task -->
        <bean id="taskTest" class="com.sawyer.job.TaskTest"/>
        <task:scheduled-tasks>
            <task:scheduled ref="taskTest" method="run" cron="0/5 * * * * ?" />
        </task:scheduled-tasks>
    </beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    3:xml配置线程池

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:task="http://www.springframework.org/schema/task"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
    
        <!-- task -->
        <context:component-scan base-package="com.sawyer.job"/>
        <task:executor id="executor" pool-size="10-15" queue-capacity="10" keep-alive="30000" rejection-policy="DISCARD"/>
        <task:scheduler id="scheduler" pool-size="10"/>
        <task:annotation-driven executor="executor" scheduler="scheduler"/>
    </beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    4:参数说明

    1:在xml中声明taskbean时

    • scheduled-tasks中可以定义多个task,这里指定了一个task,上图中 ref 指定任务类,method指定执行方法,cron指定频率,这里表示每隔5秒执行一下。
    • task中用于指定时间频率的方式,有以下几种:
      • cron:cron表达式十分强大,可以指定秒、分、时、日期、月份、星期几,格式为 * * * * * ?
      • fixed-rate:单位毫秒,每隔指定时间就执行一次
      • fixed-delay:单位毫秒,上次任务执行完后,间隔指定时间后执行下次任务
      • initial-delay:单位毫秒,首次执行任务的时候,延迟指定时间执行。
    • spring task 默认使用的是同步模式,即上次任务执行完后,才会执行下次任务。上述时间频率只有在非同步模式下才会完全符合,在同步模式下,实际计算方式为:
      • fixed-rate :任务的实际执行时间+fixedRate时间之后,执行下次任务
      • fixed-delay:任务的实际执行时间如果小于fixedDelay,则时间间隔为fixedDelay;如果任务的实际执行时间大于fixedDelay,则上次任务执行完后,立即执行下一次任务。

    2:在xml中配置线程池

    • 使用@Async开启异步模式,@Async的值为执行器executor,名字需要与xml中配置的一致。
    • executor用于配置线程池
    • pool-size:线程池数量,可以设置范围,也可以设置指定值,最小值为1,最大值为Integer.MAX_VALUE。
    • queue-capacity:任务队列,当线程数达到最小值时,新任务将会被放到队列中。当队列被占满时,executor就会在线程池中创建新的线程,执行新的任务。
    • keep-alive:pool-size的最小值是指核心线程的数量,超过这个数的其他线程,当执行完任务后,可以存活keep-alive指定的时间,单位毫秒。
    • rejection-policy:当线程数达到最大值时,系统的处理策略,可以设置4种方式:
      • ABOAT:默认值,抛出异常,不再执行新的任务,直到有空闲线程可以使用
      • DISCARD:不抛出异常,不再执行新的任务,知道有空闲线程可以使用
      • CALLER_RUNS:在当前线程中执行新的任务
      • DISCARD_OLDEST:丢弃最旧的一个任务,空出线程执行新的任务

    3:Cron表达式

    1:CronTrigger配置格式:

    格式: [秒] [分] [小时] [日] [月] [周] [年]
    在这里插入图片描述

    2:通配符说明:

    • [* ] 表示所有值. 例如:在分的字段上设置 “*”,表示每一分钟都会触发。
    • ? 表示不指定值。使用的场景为不需要关心当前设置这个字段的值。例如:要在每月的10号触发一个操作,但不关心是周几,所以需要周位置的那个字段设置为"?" 具体设置为 0 0 0 10 * ?
      • 表示区间。例如 在小时上设置 “10-12”,表示 10,11,12点都会触发。
    • , 表示指定多个值,例如在周字段上设置 “MON,WED,FRI” 表示周一,周三和周五触发
    • / 用于递增触发。如在秒上面设置"5/15" 表示从5秒开始,每增15秒触发(5,20,35,50)。在月字段上设置’1/3’所示每月1号开始,每隔三天触发一次。
    • L 表示最后的意思。在日字段设置上,表示当月的最后一天(依据当前月份,如果是二月还会依据是否是润年[leap]), 在周字段上表示星期六,相当于"7"或"SAT"。如果在"L"前加上数字,则表示该数据的最后一个。例如在周字段上设置"6L"这样的格式,则表示“本月最后一个星期五"
    • W 表示离指定日期的最近那个工作日(周一至周五). 例如在日字段上设置"15W",表示离每月15号最近的那个工作日触发。如果15号正好是周六,则找最近的周五(14号)触发, 如果15号是周未,则找最近的下周一(16号)触发.如果15号正好在工作日(周一至周五),则就在该天触发。如果指定格式为 “1W”,它则表示每月1号往后最近的工作日触发。如果1号正是周六,则将在3号下周一触发。(注,“W"前只能设置具体的数字,不允许区间”-").
    • 【#】序号(表示每月的第几个周几),例如在周字段上设置"6#3"表示在每月的第三个周六.注意如果指定"#5",正好第五周没有周六,则不会触发该配置(用在母亲节和父亲节再合适不过了)
      tips

    3:举例说明

    表达式说明
    0 0 12 * * ?每天12点触发
    0 15 10 ? * *每天10点15分触发
    0 15 10 * * ?每天10点15分触发
    0 15 10 * * ? *每天10点15分触发
    0 15 10 * * ?2005 2005年每天10点15分触发
    0 * 14 * * ?每天下午的 2点到2点59分每分触发
    0 0/5 14 * * ?每天下午的 2点到2点59分(整点开始,每隔5分触发)
    0 0/5 14,18 * * ?每天下午的 2点到2点59分(整点开始,每隔5分触发)每天下午的 18点到18点59分(整点开始,每隔5分触发)
    0 0-5 14 * * ?每天下午的 2点到2点05分每分触发
    0 10,44 14 ? 3 WED3月分每周三下午的 2点10分和2点44分触发
    0 15 10 ? * MON-FRI从周一到周五每天上午的10点15分触发
    0 15 10 15 * ?每月15号上午10点15分触发
    0 15 10 L * ?每月最后一天的10点15分触发
    0 15 10 ? * 6L每月最后一周的星期五的10点15分触发
    0 15 10 ? * 6L 2002-2005从2002年到2005年每月最后一周的星期五的10点15分触发
    0 15 10 ? * 6#3每月的第三周的星期五开始触发
    0 0 12 1/5 * ?每月的第一个中午开始每隔5天触发一次
    0 11 11 11 11 ?每年的11月11号 11点11分触发(光棍节)

    4:在线cron表达式生成: http://qqe2.com/cron/inde

  • 相关阅读:
    GitHub详解:代码托管与协作开发平台
    Html 引入element UI + vue3 报错Failed to resolve component: el-button
    Eclipse安装配置、卸载教程(Windows版)
    Mybatis动态sql和分页
    华为HCIE云计算之FA云桌面发放(Microsoft AD方式)
    贪心算法-----------------装箱问题
    浅析电力监控在新型数据中心的设计和应用-Susie 周
    【大话设计模式】开放-封闭原则
    K8S管理工具-kubectl ①
    论文阅读KVQ: Kwai Video Quality Assessment for Short-form Videos
  • 原文地址:https://blog.csdn.net/qq_41694906/article/details/125594085