Spring Boot 与 Kotlin 定时任务(Scheduling Tasks)

在编写Spring Boot应用中会遇到这样的场景,比如:需要定时地发送一些短信、邮件之类的操作,也可能会定时地检查和监控一些标志、参数等。

创建定时任务

在Spring Boot中编写定时任务是非常简单的事,下面通过实例介绍如何在Spring Boot中创建定时任务,实现每过5秒输出一下当前时间。

在Spring Boot的主类中加入@EnableScheduling注解,启用定时任务的配置


import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.scheduling.annotation.EnableScheduling


/**
 * Created by http://quanke.name on 2018/1/12.
 */


@SpringBootApplication
@EnableScheduling
class Application

fun main(args: Array<String>) {
    SpringApplication.run(Application::class.java, *args)
}

创建定时任务实现类


import org.apache.commons.logging.LogFactory
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.text.SimpleDateFormat
import java.util.*


/**
 * Created by http://quanke.name on 2018/1/12.
 */
@Component
class ScheduledTasks {

    val log = LogFactory.getLog(ScheduledTasks::class.java)!!

    private val dateFormat = SimpleDateFormat("HH:mm:ss")

    @Scheduled(fixedRate = 1000)
    fun reportCurrentTime() {
        log.info("现在时间 , ${dateFormat.format(Date())}")
    }
}

运行程序,控制台中可以看到类似如下输出,定时任务开始正常运作了。

2018-01-21 23:09:01.112  INFO 23832 --- [           main] n.q.kotlin.chaper11_8_1.ApplicationKt    : Started ApplicationKt in 8.024 seconds (JVM running for 8.724)
2018-01-21 23:09:02.112  INFO 23832 --- [pool-2-thread-1] n.q.k.chaper11_8_1.task.ScheduledTasks   : 现在时间 , 23:09:02
2018-01-21 23:09:03.042  INFO 23832 --- [pool-2-thread-1] n.q.k.chaper11_8_1.task.ScheduledTasks   : 现在时间 , 23:09:03
2018-01-21 23:09:04.042  INFO 23832 --- [pool-2-thread-1] n.q.k.chaper11_8_1.task.ScheduledTasks   : 现在时间 , 23:09:04
2018-01-21 23:09:05.042  INFO 23832 --- [pool-2-thread-1] n.q.k.chaper11_8_1.task.ScheduledTasks   : 现在时间 , 23:09:05

@Scheduled详解

在上面的入门例子中,使用了@Scheduled(fixedRate = 1000) 注解来定义每过1秒执行的任务,对于@Scheduled的使用可以总结如下几种方式:

  • @Scheduled(fixedRate = 1000) :上一次开始执行时间点之后1秒再执行
  • @Scheduled(fixedDelay = 1000) :上一次执行完毕时间点之后1秒再执行
  • @Scheduled(initialDelay=1000, fixedRate=5000) :第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
  • @Scheduled(cron=”/1 * * * *”) :通过cron表达式定义规则

@Scheduled 注解是单线程的,如果需要多线程,请增加@Async

更多Spring Boot 和 kotlin相关内容

欢迎关注《Spring Boot 与 kotlin 实战》

欢迎关注公众号《全栈架构》

全科龙婷

全栈有风险,菜鸟需谨慎

Executing pre-compile tasks… Running 'before' tasks Checking sources Copying resources… [soms] Dependency analysis found 0 affected files Updating dependency information… [soms] Parsing java… [soms] java: 无法找到类型 'kotlin.jvm.internal.SourceDebugExtension' 的注释方法 'value()': 找不到kotlin.jvm.internal.SourceDebugExtension的类文件 java: 无法找到类型 'kotlin.jvm.internal.SourceDebugExtension' 的注释方法 'value()' java: You aren't using a compiler supported by lombok, so lombok will not work and has been disabled. Your processor is: org.jetbrains.jps.javac.$Proxy8 Lombok supports: sun/apple javac 1.6, ECJ java: 来自注释处理程序 'org.mapstruct.ap.MappingProcessor' 的受支持 source 版本 'RELEASE_6' 低于 -source '1.8' java: 没有处理程序要使用以下任何注释: com.fasterxml.jackson.annotation.JsonProperty,org.springframework.data.repository.query.Param,org.springframework.web.bind.annotation.RequestParam,org.mapstruct.Mapping,net.sf.jasperreports.functions.annotations.FunctionCategory,org.springframework.beans.factory.annotation.Autowired,javax.validation.constraints.NotEmpty,javax.validation.Valid,org.apache.ibatis.type.MappedJdbcTypes,org.springframework.stereotype.Repository,org.springframework.web.bind.annotation.PostMapping,javax.annotation.Resource,javax.validation.constraints.Pattern.List,javax.validation.constraints.NotNull,org.springframework.web.bind.annotation.RestController,com.huawei.it.jalor5.core.annotation.JalorResource,io.swagger.v3.oas.annotations.tags.Tag,org.springframework.context.annotation.Lazy,io.swagger.v3.oas.annotations.responses.ApiResponses,com.alibaba.fastjson.annotation.JSONField,org.springframework.scheduling.annotation.EnableAsync,org.springframework.context.annotation.PropertySource,org.springframework.boot.context.properties.ConfigurationProperties,org.springframework.scheduling.annotation.Scheduled,org.springframework.context.annotation.Scope,org.springframework.web.bind.annotation.RequestBody,org.springframework.beans.factory.annotation.Value,io.swagger.v3.oas.annotations.Operation,org.springframework.stereotype.Service,org.springframework.web.bind.annotation.ExceptionHandler,javax.inject.Named,org.springframework.scheduling.annotation.EnableScheduling,javax.annotation.Nullable,org.springframework.web.bind.annotation.ControllerAdvice,org.springframework.validation.annotation.Validated,org.apache.ibatis.annotations.Param,org.springframework.boot.autoconfigure.SpringBootApplication,javax.xml.bind.annotation.XmlRootElement,org.apache.ibatis.type.Alias,com.huawei.it.jalor5.core.annotation.NoJalorTransation,com.huawei.it.jalor5.core.annotation.JalorOperation,org.apache.logging.log4j.core.config.plugins.validation.constraints.NotBlank,com.huawei.it.isrp.common.config.retry.Retryable,org.springframework.web.bind.annotation.PathVariable,javax.validation.constraints.Size,javax.validation.constraints.Min.List,org.springframework.web.bind.annotation.PutMapping,org.mapstruct.Mapper,com.fasterxml.jackson.annotation.JsonAlias,javax.ws.rs.DefaultValue,javax.validation.constraints.Max,org.apache.ibatis.annotations.MapKey,org.springframework.data.annotation.Transient,org.springframework.web.bind.annotation.DeleteMapping,io.swagger.v3.oas.annotations.media.Schema,javax.validation.constraints.Min,org.apache.ibatis.type.MappedTypes,com.fasterxml.jackson.annotation.JsonFormat,com.google.gson.annotations.SerializedName,io.swagger.v3.oas.annotations.Parameter,org.springframework.context.annotation.Configuration,org.jetbrains.annotations.Nullable,javax.validation.constraints.Pattern,org.apache.ibatis.annotations.Mapper,javax.annotation.PostConstruct,org.springframework.web.bind.annotation.RequestHeader,org.jetbrains.annotations.NotNull,org.hibernate.validator.constraints.Length,org.springframework.scheduling.annotation.Async,org.mapstruct.Mappings,javax.validation.constraints.NotBlank,javax.validation.constraints.Size.List,org.springframework.web.bind.annotation.RequestMapping,javax.validation.constraints.DecimalMin,org.hibernate.validator.constraints.Range,java.lang.FunctionalInterface,javax.inject.Inject,net.sf.jasperreports.functions.annotations.FunctionCategories,com.fasterxml.jackson.annotation.JsonIgnore,org.springframework.beans.factory.annotation.Qualifier,org.springframework.web.bind.annotation.GetMapping,net.sf.jasperreports.functions.annotations.Function,org.springframework.web.bind.annotation.ResponseBody,net.sf.jasperreports.functions.annotations.FunctionParameters,org.springframework.stereotype.Component,javax.validation.constraints.DecimalMax,com.fasterxml.jackson.annotation.JsonInclude,org.springframework.context.annotation.Bean,com.google.common.annotations.VisibleForTesting,org.springframework.transaction.annotation.Transactional Dependency analysis found 0 affected files Errors occurred while compiling module 'soms' javac 8 was used to compile java sources Finished, saving caches… Compilation failed: errors: 1; warnings: 17 Executing post-compile tasks… Synchronizing output directories… 2025/8/7 15:16 - Build completed with 1 error and 9 warnings in 6 sec, 749 ms 使用中文给出解决方案
08-08
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值