Grails 的定时任务功能

实现方法

  1. 定义一个 service 类
  2. 添加注解@Scheduled
  3. 强制 service bean 对象提前创建 lazyInit = false
  4. 添加 @EnableScheduling 注解

完整代码

@Slf4j 
@CompileStatic 
class HelloWorldJobService {

    static lazyInit = false 

    @Scheduled(fixedDelay = 10000L)
    void executeEveryTen() {
        log.info "Simple Job every 10 seconds :{}", new SimpleDateFormat("dd/M/yyyy hh:mm:ss").format(new Date())
    }

    @Scheduled(fixedDelay = 45000L, initialDelay = 5000L) 
    void executeEveryFourtyFive() {
        log.info "Simple Job every 45 seconds :{}", new SimpleDateFormat("dd/M/yyyy hh:mm:ss").format(new Date())
    }
}

grails-app/init/demo/Application.groovy

package demo

import grails.boot.GrailsApp
import grails.boot.config.GrailsAutoConfiguration
import groovy.transform.CompileStatic
import org.springframework.context.annotation.ComponentScan
import org.springframework.scheduling.annotation.EnableScheduling

@CompileStatic
@ComponentScan('demo') 
@EnableScheduling 
class Application extends GrailsAutoConfiguration {
    static void main(String[] args) {
        GrailsApp.run(Application, args)
    }
}

常见问题

一开始在某些项目中“定时服务”并不能正常工作,经过排查,发现原来是因为漏掉了 @EnableScheduling 注解,加上后,问题解决。

参考文章

grails scheduled guide

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值