首页 > 其他分享 >SpringBoot学习-(十九)SpringBoot定时器#Schedule

SpringBoot学习-(十九)SpringBoot定时器#Schedule

时间:2022-10-11 17:00:47浏览次数:55  
标签:INFO 10 定时器 SpringBoot 17 Schedule 16 2017 logback


定时器概述

后台项目开发中经常会用到定时器,现在实现定时器的方式也是多种多样。下面列举几种常见的定时器实现方式:

  1. Quartz:Quartz的使用相当广泛,它是一个功能强大的调度器,当然使用起来也相对麻烦;
  2. java.util包里的Timer,它也可以实现定时任务但是功能过于单一所有使用很少。
  3. 就是我们今天要介绍的Spring自带的定时任务Schedule,其实可以把它看作是一个简化版的,轻量级的Quartz,使用起来也相对方便很多。

使用步骤

  1. 配置Schedule
  2. 书写定时器类

配置Schedule

package com.ahut.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
*
* @ClassName: ScheduleConfig
* @Description: 配置定时器
* @author cheng
* @date
@Configuration
@EnableScheduling
public class ScheduleConfig

书写定时器类

package com.ahut.schedule;

import java.text.MessageFormat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
*
* @ClassName: ScheduledTasks
* @Description: 自定义定时器任务
* @author cheng
* @date
@Component
public class ScheduledTasks

// 日志
private Logger log = LoggerFactory.getLogger(this.getClass());

private int fixedDelayCount = 1;

/**
*
* @Title: testFixDelay
* @Description:表示上一次任务执行完成后多久再次执行,参数类型为long,单位ms;
*/
@Scheduled(fixedDelay = 5000)
public void testFixDelay() {
log.info(MessageFormat.format("fixedDelay()第{0}次执行", fixedDelayCount++));
}

}

执行结果:

2017-10-16 17:07:36.911 logback [MessageBroker-1] INFO  com.ahut.schedule.ScheduledTasks - fixedDelay()第1次执行
2017-10-16 17:07:36.918 logback [restartedMain] INFO o.a.coyote.http11.Http11NioProtocol - Initializing ProtocolHandler ["http-nio-8080"]
2017-10-16 17:07:36.940 logback [restartedMain] INFO o.a.coyote.http11.Http11NioProtocol - Starting ProtocolHandler ["http-nio-8080"]
2017-10-16 17:07:36.963 logback [restartedMain] INFO o.a.tomcat.util.net.NioSelectorPool - Using a shared selector for servlet write/read
2017-10-16 17:07:37.005 logback [restartedMain] INFO o.s.b.c.e.t.TomcatEmbeddedServletContainer - Tomcat started on port(s): 8080 (http)
2017-10-16 17:07:37.034 logback [restartedMain] INFO com.ahut.AhutApplication - Started AhutApplication in 8.228 seconds (JVM running for 9.71)
2017-10-16 17:07:41.912 logback [MessageBroker-2] INFO com.ahut.schedule.ScheduledTasks - fixedDelay()第2次执行
2017-10-16 17:07:46.914 logback [MessageBroker-3] INFO com.ahut.schedule.ScheduledTasks - fixedDelay()第3次执行
2017-10-16 17:07:51.915 logback [MessageBroker-3] INFO com.ahut.schedule.ScheduledTasks - fixedDelay()第4次执行
2017-10-16 17:07:56.920 logback [MessageBroker-3] INFO com.ahut.schedule.ScheduledTasks - fixedDelay()第5次执行
2017-10-16 17:08:01.923 logback [MessageBroker-3] INFO com.ahut.schedule.ScheduledTasks - fixedDelay()第6次执行
2017-10-16 17:08:06.924 logback [MessageBroker-2] INFO com.ahut.schedule.ScheduledTasks - fixedDelay()第7次执行
2017-10-16 17:08:11.926 logback [MessageBroker-2] INFO com.ahut.schedule.ScheduledTasks - fixedDelay()第8次执行
2017-10-16 17:08:16.928 logback [MessageBroker-2] INFO com.ahut.schedule.ScheduledTasks - fixedDelay()第9次执行
2017-10-16 17:08:21.928 logback [MessageBroker-2] INFO com.ahut.schedule.ScheduledTasks - fixedDelay()第10次执行

方法:

private int fixedRateCount = 1;

/**
*
* @Title: testFixedRate
* @Description:fixedRate = 5000表示当前方法开始执行5000ms后,Spring scheduling会再次调用该方法
*/
@Scheduled(fixedRate = 5000)
public void testFixedRate() {
log.info(MessageFormat.format("fixedRate: 第{0}次执行方法", fixedRateCount++));
}

执行结果:

2017-10-16 17:10:41.629 logback [MessageBroker-1] INFO  com.ahut.schedule.ScheduledTasks - fixedRate: 第1次执行方法
2017-10-16 17:10:41.636 logback [restartedMain] INFO o.a.coyote.http11.Http11NioProtocol - Initializing ProtocolHandler ["http-nio-8080"]
2017-10-16 17:10:41.655 logback [restartedMain] INFO o.a.coyote.http11.Http11NioProtocol - Starting ProtocolHandler ["http-nio-8080"]
2017-10-16 17:10:41.685 logback [restartedMain] INFO o.a.tomcat.util.net.NioSelectorPool - Using a shared selector for servlet write/read
2017-10-16 17:10:41.720 logback [restartedMain] INFO o.s.b.c.e.t.TomcatEmbeddedServletContainer - Tomcat started on port(s): 8080 (http)
2017-10-16 17:10:41.729 logback [restartedMain] INFO com.ahut.AhutApplication - Started AhutApplication in 6.266 seconds (JVM running for 7.315)
2017-10-16 17:10:46.628 logback [MessageBroker-2] INFO com.ahut.schedule.ScheduledTasks - fixedRate: 第2次执行方法
2017-10-16 17:10:51.629 logback [MessageBroker-3] INFO com.ahut.schedule.ScheduledTasks - fixedRate: 第3次执行方法
2017-10-16 17:10:56.629 logback [MessageBroker-2] INFO com.ahut.schedule.ScheduledTasks - fixedRate: 第4次执行方法
2017-10-16 17:11:01.629 logback [MessageBroker-2] INFO com.ahut.schedule.ScheduledTasks - fixedRate: 第5次执行方法
2017-10-16 17:11:06.630 logback [MessageBroker-4] INFO com.ahut.schedule.ScheduledTasks - fixedRate: 第6次执行方法
2017-10-16 17:11:11.631 logback [MessageBroker-3] INFO com.ahut.schedule.ScheduledTasks - fixedRate: 第7次执行方法
2017-10-16 17:11:16.630 logback [MessageBroker-3] INFO com.ahut.schedule.ScheduledTasks - fixedRate: 第8次执行方法
2017-10-16 17:11:21.631 logback [MessageBroker-3] INFO com.ahut.schedule.ScheduledTasks - fixedRate: 第9次执行方法

方法:

private int initialDelayCount = 1;

/**
*
* @Title: testInitialDelay
* @Description:initialDelay =1000表示延迟1000ms执行第一次任务
*/
@Scheduled(initialDelay = 1000, fixedRate = 5000)
public void testInitialDelay() {
log.info(MessageFormat.format("initialDelay: 第{0}次执行方法", initialDelayCount++));
}

执行结果:

2017-10-16 17:44:11.217 logback [MessageBroker-1] INFO  com.ahut.schedule.ScheduledTasks - initialDelay: 第1次执行方法
2017-10-16 17:44:16.216 logback [MessageBroker-2] INFO com.ahut.schedule.ScheduledTasks - initialDelay: 第2次执行方法
2017-10-16 17:44:21.217 logback [MessageBroker-3] INFO com.ahut.schedule.ScheduledTasks - initialDelay: 第3次执行方法
2017-10-16 17:44:26.217 logback [MessageBroker-3] INFO com.ahut.schedule.ScheduledTasks - initialDelay: 第4次执行方法
2017-10-16 17:44:31.217 logback [MessageBroker-3] INFO com.ahut.schedule.ScheduledTasks - initialDelay: 第5次执行方法

方法:

private int cronCount = 1;

/**
*
* @Title: testCron
* @Description:cron接受cron表达式,根据cron表达式确定定时规则
*/
@Scheduled(cron = "*/6 * * * * ?")
public void testCron() {
log.info(MessageFormat.format("core: 第{0}次执行方法", cronCount++));
}

执行结果:

2017-10-16 17:47:06.009 logback [MessageBroker-1] INFO  com.ahut.schedule.ScheduledTasks - core: 第1次执行方法
2017-10-16 17:47:12.007 logback [MessageBroker-2] INFO com.ahut.schedule.ScheduledTasks - core: 第2次执行方法
2017-10-16 17:47:18.001 logback [MessageBroker-3] INFO com.ahut.schedule.ScheduledTasks - core: 第3次执行方法
2017-10-16 17:47:24.001 logback [MessageBroker-2] INFO com.ahut.schedule.ScheduledTasks - core: 第4次执行方法
2017-10-16 17:47:30.002 logback [MessageBroker-2] INFO com.ahut.schedule.ScheduledTasks - core: 第5次执行方法

分析

@Scheduled 注解源码如下

/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.scheduling.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* An annotation that marks a method to be scheduled. Exactly one of
* the {@link #cron()}, {@link #fixedDelay()}, or {@link #fixedRate()}
* attributes must be specified.
*
* <p>The annotated method must expect no arguments. It will typically have
* a {@code void} return type; if not, the returned value will be ignored
* when called through the scheduler.
*
* <p>Processing of {@code @Scheduled} annotations is performed by
* registering a {@link ScheduledAnnotationBeanPostProcessor}. This can be
* done manually or, more conveniently, through the {@code <task:annotation-driven/>}
* element or @{@link EnableScheduling} annotation.
*
* <p>This annotation may be used as a <em>meta-annotation</em> to create custom
* <em>composed annotations</em> with attribute overrides.
*
* @author Mark Fisher
* @author Dave Syer
* @author Chris Beams
* @since 3.0
* @see EnableScheduling
* @see ScheduledAnnotationBeanPostProcessor
* @see
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled {

/**
* A cron-like expression, extending the usual UN*X definition to include
* triggers on the second as well as minute, hour, day of month, month
* and day of week. e.g. {@code "0 * * * * MON-FRI"} means once per minute on
* weekdays (at the top of the minute - the 0th second).
* @return an expression that can be parsed to a cron schedule
* @see
String cron() default "";

/**
* A time zone for which the cron expression will be resolved. By default, this
* attribute is the empty String (i.e. the server's local time zone will be used).
* @return a zone id accepted by {@link java.util.TimeZone#getTimeZone(String)},
* or an empty String to indicate the server's default time zone
* @since 4.0
* @see org.springframework.scheduling.support.CronTrigger#CronTrigger(String, java.util.TimeZone)
* @see
String zone() default "";

/**
* Execute the annotated method with a fixed period in milliseconds between the
* end of the last invocation and the start of the next.
* @return
long fixedDelay() default -1;

/**
* Execute the annotated method with a fixed period in milliseconds between the
* end of the last invocation and the start of the next.
* @return the delay in milliseconds as a String value, e.g. a placeholder
* @since
String fixedDelayString() default "";

/**
* Execute the annotated method with a fixed period in milliseconds between
* invocations.
* @return
long fixedRate() default -1;

/**
* Execute the annotated method with a fixed period in milliseconds between
* invocations.
* @return the period in milliseconds as a String value, e.g. a placeholder
* @since
String fixedRateString() default "";

/**
* Number of milliseconds to delay before the first execution of a
* {@link #fixedRate()} or {@link #fixedDelay()} task.
* @return the initial delay in milliseconds
* @since
long initialDelay() default -1;

/**
* Number of milliseconds to delay before the first execution of a
* {@link #fixedRate()} or {@link #fixedDelay()} task.
* @return the initial delay in milliseconds as a String value, e.g. a placeholder
* @since
String initialDelayString() default "";

}
  • cron:cron表达式,指定任务在特定时间执行;
  • fixedDelay:表示上一次任务执行完成后多久再次执行,参数类型为long,单位ms;
  • fixedDelayString:与fixedDelay含义一样,只是参数类型变为String;
  • fixedRate:表示按一定的频率执行任务,参数类型为long,单位ms;
  • fixedRateString: 与fixedRate的含义一样,只是将参数类型变为String;
  • initialDelay:表示延迟多久再第一次执行任务,参数类型为long,单位ms;
  • initialDelayString:与initialDelay的含义一样,只是将参数类型变为String;
  • zone:时区,默认为当前时区,一般没有用到。


标签:INFO,10,定时器,SpringBoot,17,Schedule,16,2017,logback
From: https://blog.51cto.com/u_15824687/5747163

相关文章

  • SpringBoot学习-(十五)SpringBoot热部署
    热部署最重要的功能就是自动应用代码更改到最新的App上面去。原理是在发现代码有更改之后,重新启动应用,但是比速度比手动停止后再启动还要更快,更快指的不是节省出来的手工操......
  • 正点原子->实验8 定时器中断实验
    定时器初始化:1.定时器初始化2.中断初始化voidTIM3_Int_Init(u16arr,u16psc){TIM_TimeBaseInitTypeDefTIM_TimeBaseStructure;NVIC_InitTypeDefNVIC_Ini......
  • 运行springboot是左下角没有services窗口解决方案
    结果成功:参考博文:http://t.zoukankan.com/sxdcgaq8080-p-14543088.html......
  • SpringBoot整合ssh
    背景:测试环境连接生产环境的数据库,无法本地调试环境: JDK8Maven:3.6.3Springboot:2.1.4jsch:0.1.55Jsch百度百科介绍:JSch是SSH2的一个纯Java实现。它允许你连......
  • springboot2中多环境配置@@ 无法解析maven中的设置
    Maven(pom中设置环境)SpringBoot(yml中设置多环境)都具备对环境的开发控制maven优先度高于springboot,springboot基于maven的坐标配置需要在pom.xml中配置多环境开......
  • springboot~对mybatis的start包进行单元测试
    一个start包,它不需要有springboot启动类,它只提供一切公用的功能,被其它包依赖就行了,通过META-INF/spring.factories或者META-INF/spring/org.springframework.boot.autoconf......
  • springboot H2 linux下搭建使用
    这次研究是H2数据库了,关键还是再Linux下进行搭建部署的,被这个数据库快弄死了弄了4天时间,现在大致可以用了,还有些细节需要修正。我这边使用的是springboot集成模式。直接使......
  • Springboot 日志框架
    1、概述项目中日志系统是必不可少的的。目前比较流行的日志框架有log4j、logback等。可能大家还不知道,这两个框架的作者是同一个人,Logback旨在作为流行的log4j项目的后......
  • 执行定时任务:使用Windows service创建定时器
    一、需求创建一个定时任务,定时执行数据处理任务,并记录日志,发送邮件。本篇使用的方法:windowsservice 定时任务常用的实现方法可参考大佬文章:Windows自动定时执行任务的......
  • 郁金香 用C写一个定时器来循环获取阳光
    先来张效果图定时器代码 HWND游戏窗口句柄=FindWindowA("MainWindow","植物大战僵尸中文版");::SetTimer(游戏窗口句柄,4567,UINT_PTR(1000),阳光回调)......