grails 从 quartz 作业中调用 taglib

grails call taglib from quartz job

我有一个调用 joda taglib 的 quartz 作业(但可以是任何其他的)。

我是这样做的:

def joda = grailsApplication.mainContext.getBean('grails.plugin.jodatime.taglib.FormattingTagLib')

def formatDate = joda.format(value:event.startDate, style:"SS", locale:user.locale, zone:user.timeZone)

但是我得到了:

org.quartz.JobExecutionException: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request. [See nested exception: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.]

这绝对有道理,因为 quartz 作业不受请求约束,因为它是由时间触发的,而不是由请求触发的。

我四处寻找但找不到合适的解决方案。有人可以给我提示吗?

问题是 joda.format() 尝试获取当前请求,如您所述,这是不可能的。

但更根本的是,taglibs 是为 GSP 服务的。在 GSP 之外调用它们不是一个好的做法,因为它在 taglibs 的用例之外。幸运的是,解决方案很简单:直接使用 joda 时间格式化程序:

import org.joda.time.format.DateTimeFormat

def formatter = DateTimeFormat.forStyle('SS').withLocale(user.locale).withZone(user.timeZone)
def formatDate = formatter.print(event.startDate)

https://github.com/gpc/joda-time/blob/grails2/grails-app/taglib/grails/plugin/jodatime/taglib/FormattingTagLib.groovy

如何从quartz job中调用taglib的答案是根本不做。