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个域

[秒] [分] [小时] [日] [月] [周] [年]
序号说明必填允许填写的值允许的通配符
10-59, - * /
20-59, - * /
30-23, - * /
41-31, - * ? / L W
51-12 / JAN-DEC, - * /
61-7 or SUN-SAT, - * ? / L #
71970-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 * * ?"));
    }
}
  • 29
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBootJava语言的一种开放源代码框架,可以快速构建基于Spring框架的Web应用程序。而mybatis-plus是基于mybatis的增强工具,可以进一步简化mybatis的使用,提高开发效率。 定时器管理是指定时执行某些任务,比如定时清理缓存、定时备份数据库等。在SpringBoot中,可以使用@Scheduled注解来实现定时任务。而基于mybatis-plus的定时器管理,可以通过创建一个定时任务执行器的实体类,并使用mybatis-plus提供的BaseMapper进行数据库操作。 下面是一个简单的示例: 1. 创建一个定时任务执行器的实体类,例如: ```java @Data @TableName("t_schedule_task") public class ScheduleTaskEntity { @TableId(type = IdType.AUTO) private Long id; @TableField("job_name") private String jobName; @TableField("cron_expression") private String cronExpression; @TableField("job_class") private String jobClass; @TableField("job_group") private String jobGroup; @TableField("job_status") private Boolean jobStatus; @TableField("job_data") private String jobData; @TableField(fill = FieldFill.INSERT) private Date createTime; @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateTime; } ``` 2. 创建一个Mapper接口,继承mybatis-plus提供的BaseMapper,并实现一些自定义的数据库操作方法,例如: ```java public interface ScheduleTaskMapper extends BaseMapper<ScheduleTaskEntity> { List<ScheduleTaskEntity> selectByJobStatus(Boolean jobStatus); void updateByJobName(@Param("jobName") String jobName, @Param("jobStatus") Boolean jobStatus); } ``` 3. 创建一个定时任务的执行类,例如: ```java @Component public class ScheduleTaskExecutor { @Autowired private ScheduleTaskMapper scheduleTaskMapper; @Scheduled(cron = "0/5 * * * * ?") public void executeTask() { List<ScheduleTaskEntity> taskList = scheduleTaskMapper.selectByJobStatus(true); for (ScheduleTaskEntity task : taskList) { String jobName = task.getJobName(); String jobClass = task.getJobClass(); String jobGroup = task.getJobGroup(); String jobData = task.getJobData(); try { Class<?> clazz = Class.forName(jobClass); JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity(jobName, jobGroup).build(); if (StringUtils.isNotBlank(jobData)) { jobDetail.getJobDataMap().put("jobData", jobData); } Trigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName, jobGroup) .withSchedule(CronScheduleBuilder.cronSchedule(task.getCronExpression())).build(); Scheduler scheduler = new StdSchedulerFactory().getScheduler(); scheduler.scheduleJob(jobDetail, trigger); scheduler.start(); } catch (Exception e) { e.printStackTrace(); } scheduleTaskMapper.updateByJobName(jobName, false); } } } ``` 4. 在配置文件中配置数据库连接信息、mybatis-plus和定时任务的属性,例如: ```yaml spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai username: root password: root mybatis-plus: mapper-locations: classpath:/mapper/**/*.xml configuration: map-underscore-to-camel-case: true spring: task: scheduling: pool: size: 10 scheduler: pool-size: 100 ``` 5. 在启动类上加上@EnableScheduling注解,启动应用程序即可。 通过以上步骤,就可以基于mybatis-plus实现定时器管理。当数据库中的定时任务状态为true时,定时任务执行器会根据任务的cron表达式自动执行任务,并将任务状态更新为false,以避免重复执行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值