定时任务(spring/spring-boot/jdk版)

1.spring中使用定时任务(这里以spring task为例,而非quartz)

1.1引入pom文件

     <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.2.4.RELEASE</version>
    </dependency>

2.在spring配置文件中扫描定时任务所在的类,并定义注解支持

    <context:component-scan base-package="com.zy.service"/>

    <task:executor id="executor" pool-size="5"/>
    <task:scheduler id="scheduler" pool-size="10"/>
    <task:annotation-driven executor="executor" scheduler="scheduler"/>

3.定义定时任务的类,并根据情况定义规则

package com.zy.service;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class DemoTaskServiceImpl {

    // @Scheduled注解可以控制方法定时执行

    @Scheduled(fixedDelay = 30000)
    /*
    * fixedDelay控制方法执行的间隔时间,是以上一次方法执行完开始算起,
    * 如上一次方法执行阻塞住了,那么直到上一次执行完,
    * 并间隔给定的时间后,执行下一次。
    *
    * */
    public void fixedDelay(){
        System.out.println("fixedDelay" + "==========================");
    }

    @Scheduled(fixedRate = 30000)
    /*
    * fixedRate是按照一定的速率执行,是从上一次方法执行开始的时间算起,
    * 如果上一次方法阻塞住了,下一次也是不会执行,
    * 但是在阻塞这段时间内累计应该执行的次数,
    * 当不再阻塞时,一下子把这些全部执行掉,而后再按照固定速率继续执行。
    *
    * */
    public void fixedRate(){
        System.out.println("fixedRate" + "===========================");
    }

    @Scheduled(cron = "0/3 * * * * *")
    /*
    * cron表达式可以定制化执行任务,
    * 但是执行的方式是与fixedDelay相近的,也是会按照上一次方法结束时间开始算起
    *
    * */
    public void cron(){
        System.out.println("cron" + "===============================");
    }

}

2.spring-boot使用定时任务(以spring task为例)

2.1第一种方式
2.1.1pom文件

<dependencies> 
<dependency> 
<groupId>org.springframework.boot</groupId> 
<artifactId>spring-boot-starter-web</artifactId>
 </dependency>
 <dependency> 
<groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter</artifactId> 
</dependency> 
<dependency> 
<groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> 
<optional>true</optional> 
</dependency> 
<dependency> 
<groupId>org.springframework.boot</groupId> 
<artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> 
</dependency> 
</dependencies>

2.1.2定时任务类

    @Slf4j
    @Component
    public class ScheduledService {
        @Scheduled(cron = "0/5 * * * * *")
        public void scheduled() {
            log.info("=====>>>>>使用cron  {}", System.currentTimeMillis());
        }

        @Scheduled(fixedRate = 5000)
        public void scheduled1() {
            log.info("=====>>>>>使用fixedRate{}", System.currentTimeMillis());
        }

        @Scheduled(fixedDelay = 5000)
        public void scheduled2() {
            log.info("=====>>>>>fixedDelay{}", System.currentTimeMillis());
        }
    }

2.1.3启动类上添加注解=======>>>>

@EnableScheduling

三个定时任务都已经执行,并且使同一个线程中串行执行,如果只有一个定时任务,这样做肯定没问题,当定时任务增多,如果一个任务卡死,会导致其他任务也无法执行
2.2多线程执行
2.2.1在上述代码基础上添加一个配置类

    @Configuration
    @EnableAsync
    public class AsyncConfig { 
        
        @Bean
        public Executor taskExecutor() {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(10);
            executor.setMaxPoolSize(100);
            executor.setQueueCapacity(10);
            executor.initialize();
            return executor;
        }
    }
@Configuration:表明该类是一个配置类
@EnableAsync:开启异步事件的支持

2.2.2然后在定时任务的类或者方法上添加@Async即可,如:

 @Slf4j
    @Component
    public class ScheduledService {
        @Scheduled(cron = "0/5 * * * * *")
        @Async
        public void scheduled() {
            log.info("=====>>>>>使用cron  {}", System.currentTimeMillis());
        }

        @Scheduled(fixedRate = 5000)
        @Async
        public void scheduled1() {
            log.info("=====>>>>>使用fixedRate{}", System.currentTimeMillis());
        }

        @Scheduled(fixedDelay = 5000)
        @Async
        public void scheduled2() {
            log.info("=====>>>>>fixedDelay{}", System.currentTimeMillis());
        }
    }

3.cron表达式介绍

3.1简介

Cron表达式是一个字符串,字符串以5或6个空格隔开,分为6或7个域,每一个域代表一个含义,Cron有如下两种语法格式:
(1) Seconds Minutes Hours DayofMonth Month DayofWeek Year
(2)Seconds Minutes Hours DayofMonth Month DayofWeek
corn从左到右(用空格隔开):秒 分 小时 月份中的日期 月份 星期中的日期 年份

3.2表达式介绍


图片.png
(1)*:表示匹配该域的任意值。假如在Minutes域使用*, 即表示每分钟都会触发事件。
(2)?:只能用在DayofMonth和DayofWeek两个域。它也匹配域的任意值,但实际不会。因为DayofMonth和DayofWeek会相互影响。例如想在每月的20日触发调度,不管20日到底是星期几,则只能使用如下写法: 13 13 15 20 * ?, 其中最后一位只能用?,而不能使用*,如果使用*表示不管星期几都会触发,实际上并不是这样。
(3)-:表示范围。例如在Minutes域使用5-20,表示从5分到20分钟每分钟触发一次 
(4)/:表示起始时间开始触发,然后每隔固定时间触发一次。例如在Minutes域使用5/20,则意味着5分钟触发一次,而25,45等分别触发一次. 
(5),:表示列出枚举值。例如:在Minutes域使用5,20,则意味着在5和20分每分钟触发一次。 
(6)L:表示最后,只能出现在DayofWeek和DayofMonth域。如果在DayofWeek域使用5L,意味着在最后的一个星期四触发。 
(7)W:表示有效工作日(周一到周五),只能出现在DayofMonth域,系统将在离指定日期的最近的有效工作日触发事件。例如:在 DayofMonth使用5W,如果5日是星期六,则将在最近的工作日:星期五,即4日触发。如果5日是星期天,则在6日(周一)触发;如果5日在星期一到星期五中的一天,则就在5日触发。另外一点,W的最近寻找不会跨过月份 。
(8)LW:这两个字符可以连用,表示在某个月最后一个工作日,即最后一个星期五。 
(9)#:用于确定每个月第几个星期几,只能出现在DayofMonth域。例如在4#2,表示某月的第二个星期三。

3.3常用表达式例子

(1)0 0 2 1 * ? *   表示在每月的1日的凌晨2点调整任务
(2)0 15 10 ? * MON-FRI   表示周一到周五每天上午10:15执行作业
(3)0 15 10 ? 6L 2002-2006   表示2002-2006年的每个月的最后一个星期五上午10:15执行作
(4)0 0 10,14,16 * * ?   每天上午10点,下午2点,4点 
(5)0 0/30 9-17 * * ?   朝九晚五工作时间内每半小时 
(6)0 0 12 ? * WED    表示每个星期三中午12点 
(7)0 0 12 * * ?   每天中午12点触发 
(8)0 15 10 ? * *    每天上午10:15触发 
(9)0 15 10 * * ?     每天上午10:15触发 
(10)0 15 10 * * ? *    每天上午10:15触发 
(11)0 15 10 * * ? 2005    2005年的每天上午10:15触发 
(12)0 * 14 * * ?     在每天下午2点到下午2:59期间的每1分钟触发 
(13)0 0/5 14 * * ?    在每天下午2点到下午2:55期间的每5分钟触发 
(14)0 0/5 14,18 * * ?     在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发 
(15)0 0-5 14 * * ?    在每天下午2点到下午2:05期间的每1分钟触发 
(16)0 10,44 14 ? 3 WED    每年三月的星期三的下午2:10和2:44触发 
(17)0 15 10 ? * MON-FRI    周一至周五的上午10:15触发 
(18)0 15 10 15 * ?    每月15日上午10:15触发 
(19)0 15 10 L * ?    每月最后一日的上午10:15触发 
(20)0 15 10 ? * 6L    每月的最后一个星期五上午10:15触发 
(21)0 15 10 ? * 6L 2002-2005   2002年至2005年的每月的最后一个星期五上午10:15触发 
(22)0 15 10 ? * 6#3   每月的第三个星期五上午10:15触发

4.jdk实现定时任务,并实现任务周期动态可配置(单线程)

package com.zy.task;

import com.netflix.config.DynamicProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
// 该类如果放到spring-boot中,该类所在的包需要与启动类平级放置,便于扫描
// 该类如果放到spring中,需要在spring配置文件中,扫描该包
public class ExecutorTaskDemo {

    private static ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();

    private Long fixedDelay = DynamicProperty.getInstance("fixedDelay").getLong();

    private void execute() {
        try {
            System.out.println(">>>>>>>>>>>>>>>>>>>>>>>try块里写循环定时执行的逻辑<<<<<<<<<<<<<<<<<<");
            // 每次业务执行完后,重新由netflix动态获取执行时间,列入下次定时任务中,其中,fixedDelay在类路径下的config.properties文件中
            fixedDelay = DynamicProperty.getInstance("fixedDelay").getLong();
        } catch (Exception e) {
            log.error("failed to execute task", e);
        } finally {
            // 无论如何,都会执行该方法
            executorService.schedule(()->execute(), fixedDelay, TimeUnit.SECONDS);
        }
    }

    @PostConstruct
    public void initMethod(){
        // 定时任务的触发点,该bean初始化后,执行该方法
        execute();
    }

}
图片.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容