ServletContextHolder.servletContext returning null in Quartz jobs
- Dominant language
- Groovy
- Stars
- 2.9k
- Forks
- 975
- Avg merge
- 1d 22h
- Merged PRs (30d)
- 92
Description
### Expected Behavior
We are currently of upgrading a Grails project to the latest version and I have noticed an issue with the Quartz plugin. Basically, in Quartz jobs we are getting a null object when reading this
`grails.web.context.ServletContextHolder.servletContext`
It was working fine up to the latest version of Grails 3.3.14 but then it does not work for Grails 4 or Grails 5. I have created different projects in each of version. You just need to start up the project with `./gradlew bootRun` and wait for a minute until a quartz job gets executed. Only for the project in Grails 3.3.14, the method grails.web.context.ServletContextHolder.getServletContext() is properly instantiated:
- Grails 3.3.14: https://github.com/frangarcia/testprojectgrails3314
- Grails 4.0.13: https://github.com/frangarcia/testprojectgrails4013
- Grails 5.1.7: https://github.com/frangarcia/testprojectgrails517
These project have been created from scratch and I have just added the dependencies in the build.gradle:
```
implementation "org.grails.plugins:quartz:2.0.13"
implementation "org.quartz-scheduler:quartz:2.3.2"
```
and created a cron job at grails-app/jobs/ExampleJob.groovy with:
```
import grails.web.context.ServletContextHolder as SCH
/**
Job to trigger the execution of customer specific reports, delivered by email
*/
class ExampleJob {
static triggers = {
simple name: 'ExampleJobTrigger', startDelay: 1 * 60000, repeatInterval: 60000
}
static group = "Reporting"
static concurrent = false //be on the safe side
def execute() {
println "*" * 200
println "SCH.servletContext = ${SCH.servletContext}"
println "*" * 200
}
}
```
### Actual Behaviour
_No response_
### Steps To Reproduce
1.- Checkout the repos
2.- Start the project with `./gradlew bootRun` and wait for a minute
### Environment Information
_No response_
### Example Application
https://github.com/frangarcia/testprojectgrails4013
### Version
4.0.13
Contributor guide
Research direction
Run the example with ./gradlew bootRun and inspect grails-app/jobs/ExampleJob.groovy, then compare the Grails 3.3.14, 4.0.13, and 5.1.7 projects and their build.gradle dependencies. Trace when ServletContextHolder is initialized relative to the Quartz job execution. Done means the behavior is explained and the appropriate project change or documented limitation is covered by a regression test or reproduction.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- groovy
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100