SpringBoot - 四种常见定时器

常见实现方案

  • @Scheduled注解:基于注解
  • Timer().schedule创建任务:基于封装类Timer
  • 线程:使用线程直接执行任务即可,可以与thread、线程池、ScheduleTask等配合使用
  • quartz配置定时器:基于springquartz框架


@Scheduled注解实现定时器

使用注解标记需要定时执行的方法,并设置执行时间,便可使其在指定的时间执行指定方法

步骤:

  • 使用注解@Scheduled标记目标方法,参数为执行时间
  • 使用注解@EnableScheduling标记目标方法所在的类,或者直接标记项目启动类

@Scheduled(fixedDelay = 5000):方法执行完成后等待5秒再次执行

@Scheduled(fixedRate = 5000):方法每隔5秒执行一次

@Scheduled(initialDelay=1000, fixedRate=5000):延迟1秒后执行第一次,之后每隔5秒执行一次

fixedDelayString、fixedRateString、initialDelayString:与上诉三种作用一直,但参数为字符串类型,因而可以使用占位符,形如@Scheduled(fixedDelayString = "${time.fixedDelay}")

@Scheduled(cron = "0 0,30 0,8 ? * ? "):方法在每天的8点30分0秒执行,参数为字符串类型,那么同理也可使用占位符

cron 该参数接收一个cron表达式cron表达式是一个字符串,字符串以5或6个空格隔开,分开共6或7个域,[年]不是必须的域,可以省略[年],则一共6个域

[秒] [分] [小时] [日] [月] [周] [年]
序号 说明 必填 允许填写的值 允许的通配符
1 0-59 , - * /
2 0-59 , - * /
3 0-23 , - * /
4 1-31 , - * ? / L W
5 1-12 / JAN-DEC , - * /
6 1-7 or SUN-SAT , - * ? / L #
7 1970-2099 , - * /

通配符说明:

  • * 表示所有值。 例如:在分的字段上设置 *,表示每一分钟都会触发。
  • ? 表示不指定值。使用的场景为不需要关心当前设置这个字段的值。例如:要在每月的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”,正好第五周没有周六,则不会触发该配置(用在母亲节和父亲节再合适不过了) ;小提示:’L’和 ‘W’可以一组合使用。如果在日字段上设置”LW”,则表示在本月的最后一个工作日触发;周字段的设置,若使用英文字母是不区分大小写的,即MON与mon相同。

示例

每隔5秒执行一次:*/5 * * * * ?

每隔1分钟执行一次:0 */1 * * * ?

每天23点执行一次:0 0 23 * * ?

每天凌晨1点执行一次:0 0 1 * * ?

每月1号凌晨1点执行一次:0 0 1 1 * ?

每月最后一天23点执行一次:0 0 23 L * ?

每周星期六凌晨1点实行一次:0 0 1 ? * L

在26分、29分、33分执行一次:0 26,29,33 * * * ?

每天的0点、13点、18点、21点都执行一次:0 0 0,13,18,21 * * ?

使用占位符

另外,cron属性接收的cron表达式支持占位符

配置文件:

time:
  cron: */5 * * * * *
  interval: 5

每5秒执行一次:

    @Scheduled(cron="${time.cron}")
    void testPlaceholder1() {
        System.out.println("Execute at " + System.currentTimeMillis());
    }

    @Scheduled(cron="*/${time.interval} * * * * *")
    void testPlaceholder2() {
        System.out.println("Execute at " + System.currentTimeMillis());
    }

第一次等待10秒,之后每3秒一次

@Component
@EnableScheduling
public class ScheduleTest {
 
    private int count = 0;
 
    /**
     * 第一次等待10秒,之后每3秒钟执行一次
     */
    @Scheduled(initialDelay = 10000, fixedRate = 3000)
    public void test1() {
        System.out.println(count + ":" + (new Date()).toString());
        count++;
    }
 
}

 


Timer().schedule实现定时器

核心包括Timer和TimerTask,均为jkd自带的工具类

TimerTask实际上就是一个Runnable而已,继承Runnable并添加了几个自定义的参数和方法

Timer字面意思即定时器,为jkd自带的工具类,提供定时执行任务的相关功能

实际上包括三个类:

Timer:即定时器主类,负责管理所有的定时任务,每个Timer拥有一个私有的TaskQueue和TimerThread,

TaskQueue:即任务队列,Timer生产任务,然后推到TaskQueue里存放,等待处理,被处理掉的任务即被移除掉

TaskQueue实质上只有一个长度为128的数组用于存储TimerTask、一个int型变量size表示队列长度、以及对这两个数据的增删改查

TimerThread:即定时器线程,线程会共享TaskQueue里面的数据,TimerThread会对TaskQueue里的任务进行消耗

TimerThread实际上就是一个Thread线程,会不停的监听TaskQueue,如果队列里面有任务,那么就执行第一个,并将其删除(先删除再执行)

流程分析

Timer生产任务(实际上是从外部接收到任务),并将任务推到TaskQueue里面存放,并唤醒TaskQueue线程(queue.notify())
TimerThread监听TaskQueue,若里面有任务则将其执行并移除队里,若没有任务则让队列等待(queue.wait())

构造

public Timer(String name, boolean isDaemon)
  • name:即线程名,用于区分不同的线程,缺省的时候默认使用"Timer-" + serialNumber()生成唯一线程名
  • isDaemon:是否是守护线程,缺省的时候默认为否

方法

schedule(TimerTask task, long delay):指定任务task,在delay毫秒延迟后执行


schedule(TimerTask task, Date time):指定任务task,在time时间点执行一次


schedule(TimerTask task, long delay, long period):指定任务task,延迟delay毫秒后执行第一次,并在之后每隔period毫秒执行一次


schedule(TimerTask task, Date firstTime, long period):指定任务task,在firstTime的时候执行第一次,之后每隔period毫秒执行一次


scheduleAtFixedRate(TimerTask task, long delay, long period):作用与schedule一致
scheduleAtFixedRate(TimerTask task, Date firstTime, long period):作用与schedule一致

实际上最后都会使用sched(TimerTask task, long time, long period),即指定任务task,在time执行第一次,之后每隔period毫秒执行一次

schedule使用系统时间计算下一次,即System.currentTimeMillis()+period

而scheduleAtFixedRate使用本次预计时间计算下一次,即time + period

对于耗时任务,两者区别较大,请按需求选择,瞬时任务无区别

取消任务方法:cancel(),会将任务队列清空,并堵塞线程,且不再能够接受任务(接受时报错),并不会销毁本身的实例和其内部的线程

净化方法:purge(),净化会将队列里所有被取消的任务移除,对剩余任务进行堆排序,并返回移除任务的数量

@Component
public class TimerTest {
    private Integer count = 0;
 
    public TimerTest() {
        testTimer();
    }
 
    public void testTimer() {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    //do Something
                    System.out.println(new Date().toString() + ": " + count);
                    count++;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 0, 1000);
    }
}
 


线程实现定时器

使用thread + runnable

public class ThreadTest {
 
    private Integer count = 0;
 
    public ThreadTest() {
        test1();
    }
 
    public void test1() {
        new Thread(() -> {
            while (count < 10) {
                System.out.println(new Date().toString() + ": " + count);
                count++;
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

使用线程池 + runnable

public class ThreadTest {
 
    private static final ExecutorService threadPool = Executors.newFixedThreadPool(5);// 线程池
    private Integer count = 0;
 
    public ThreadTest() {
        test2();
    }
 
    public void test2() {
        threadPool.execute(() -> {
            while (count < 10) {
                System.out.println(new Date().toString() + ": " + count);
                count++;
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
 

使用org.springframework.scheduling.TaskScheduler+ runnable

设置触发频率为3000毫秒

@Component
public class ThreadTest {
 
    private Integer count = 0;
    private final TaskScheduler taskScheduler;
 
    public ThreadTest(TaskScheduler taskScheduler) {
        this.taskScheduler = taskScheduler;
        test3();
    }
 
    public void test3() {
        taskScheduler.scheduleAtFixedRate(() -> {
            System.out.println(new Date().toString() + ": " + count);
            count++;
        }, 3000);
    }
}

设置触发时间为每天凌晨1点

@Component
public class ThreadTest {
 
    private Integer count = 0;
    private final TaskScheduler taskScheduler;
 
    public ThreadTest(TaskScheduler taskScheduler) {
        this.taskScheduler = taskScheduler;
        test4();
    }
 
    public void test4() {
        taskScheduler.schedule(() -> {
            System.out.println(new Date().toString() + ": " + count);
            count++;
        }, new CronTrigger("0 0 1 * * ?"));
    }
}

相关推荐

  1. SpringBoot - 常见定时器

    2023-12-11 02:24:02       27 阅读
  2. C# 定时器的用法

    2023-12-11 02:24:02       15 阅读
  3. SpringBoot+定时器

    2023-12-11 02:24:02       16 阅读
  4. SpringBoot 中获取 Request 的方法

    2023-12-11 02:24:02       38 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-11 02:24:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-11 02:24:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-11 02:24:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-11 02:24:02       18 阅读

热门阅读

  1. 列表和双向队列的方法

    2023-12-11 02:24:02       32 阅读
  2. qt 模型视图结构

    2023-12-11 02:24:02       35 阅读
  3. TS学习——面向对象

    2023-12-11 02:24:02       37 阅读
  4. 文本转图像 学习笔记

    2023-12-11 02:24:02       39 阅读
  5. 分布式事务实现方案

    2023-12-11 02:24:02       37 阅读
  6. git上传流程

    2023-12-11 02:24:02       38 阅读
  7. MySQL 添加注释(comment)

    2023-12-11 02:24:02       35 阅读
  8. 挖漏洞之文件上传

    2023-12-11 02:24:02       35 阅读
  9. Linux C语言 41-进程间通信IPC之共享内存

    2023-12-11 02:24:02       35 阅读
  10. Linux-实现没有血缘关系的进程之间的通信

    2023-12-11 02:24:02       35 阅读