博客
关于我
springboot任务之定时任务
阅读量:485 次
发布时间:2019-03-06

本文共 1063 字,大约阅读时间需要 3 分钟。

在启动入口上加上@EnableScheduling注解,在需要定时执行的方法上加上@Scheduled注解,这是Spring Boot中实现定时任务的常用方法。以下是具体操作步骤和常见配置示例。

首先,在需要定时执行的方法上添加@Scheduled注解。这个注解的主要配置参数是cron,用于定义任务的执行时间规则。cron参数由六个部分组成,分别代表不同的时间单位:秒、分钟、小时、天、月、周几。

举个例子,以下代码展示了一个在工作日每周一到周五的整秒执行一次的定时任务:

import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Service;@Servicepublic class ScheduledService {    @Scheduled(cron = "0 * * * * MON-FRI")    public void hello() {        System.out.println("hello...");    }}

在上述代码中,cron = "0 * * * * MON-FRI"的含义是:每周一到周五的整秒执行任务一次。具体来说:

  • 0:表示任务从0秒开始执行
  • *:表示秒、分钟、小时、天、月的取值范围是0-59
  • MON-FRI:表示任务在星期一到星期五执行

除了上述简单的配置方式,还可以根据需求使用其他cron表达式。例如:

  • 在指定的秒内执行多次任务:

    @Scheduled(cron = "0,1,2,3,4 * * * * MON-FRI")
  • 在指定的时间间隔内执行任务:

    @Scheduled(cron = "0-4 * * * * MON-FRI")
  • 从某一时间开始,每隔一定间隔执行一次任务:

    @Scheduled(cron = "0/4 * * * * MON-FRI")
  • 了解了这些cron表达式后,可以根据实际需求灵活配置定时任务。

    需要注意的是,定时任务会根据@EnableScheduling注解的启用情况来执行。如果需要在启动时自动启用定时任务,记得在主类上添加@EnableScheduling注解。

    最后,启动Spring Boot应用后,控制台会输出定时任务的执行日志。例如,在13:22:00时,会输出如下的日志信息:

    hello...

    通过以上方法,可以轻松在Spring Boot应用中实现定时任务的配置和管理。

    转载地址:http://ctsbz.baihongyu.com/

    你可能感兴趣的文章
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    no1
    查看>>
    NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
    查看>>
    NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    查看>>
    Node JS: < 一> 初识Node JS
    查看>>
    Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
    查看>>
    Node-RED中使用JSON数据建立web网站
    查看>>
    Node-RED中使用json节点解析JSON数据
    查看>>
    Node-RED中使用node-random节点来实现随机数在折线图中显示
    查看>>
    Node-RED中使用node-red-browser-utils节点实现选择Windows操作系统中的文件并实现图片预览
    查看>>