Quartz job triggering from Config.groovy - grails

I have the following Quartz job running in my application:
class ScraperJob {
def scraperService
static triggers = {
cron name: 'scraperTrigger', cronExpression: "0 0 * * * ?" // run every minute
}
def execute(){
try {
scraperService.storing()
log.info "${new Date()} - Scraping went smoothly."
}
catch(IOException) { // Connexion problem
log.error "${new Date()} - Method: parsing >> Connexion down or interrupted while parsing !"
}
catch(SAXException) { // Any SAXParser exception
log.error "${new Date()} - Method: parsing >> Parser error."
}
finally { // if not closed, the application crashes when the connexion fails
scraperService.slurper.finalize()
scraperService.parser.finalize()
}
}
}
I would like to know if it is possible to set the triggers property from the Config.groovy file. If it is, could you explain how?

I have no idea if this would actually work because i'm not sure when the quartz jobs get configured but in theory it would seem to work. You could probably see how you could also make this much more dynamic if you have more than one job.
Config.groovy
quartz.yourCronJobName="0 0 * * * ?"
BootStrap.groovy
import org.codehaus.groovy.grails.commons.ConfigurationHolder as ConfigHolder
...
def cronExpression = ConfigHolder.config.yourCronJobName
ScraperJob.triggers.cronExpression = cronExpression
Good luck. Let me know if it helps.

Here is how I eventually did it:
Config.groovy
scraperJob= "0 * * * * ?"
ScraperJob.groovy
import org.codehaus.groovy.grails.commons.ConfigurationHolder as ConfigHolder
class ScraperJob {
static triggers = {
cron cronExpression: ConfigHolder.config.scraperJob // Calling the ScraperJob set in Config.groovy
}
def execute(){ ... }
}

Related

Jenkins triggers gets depreciated

I have the below piece of code in groovy to schedule the job at 12 am IST.
I am using Job DSL plugin to seed the job.
Initial code-
triggers{
cron{
spec("TZ=Asia/Calcutta\n0 0 * * *")
}
}
For the same even though it works, I get depreciation warnings.
Warning: (jobName.groovy, line 18) triggers is deprecated
Second code-
void nightly(String schedule = 'H 0 * * *') {
job.properties {
pipelineTriggers {
triggers{
cron{
spec("TZ=Asia/Calcutta\nH 0 * * *")
}
}
}
}
}
The second one got failed with the below error message.
JobScriptsSpec > test script fr_oms_core_unit_perf_sanity_job.groovy FAILED
org.spockframework.runtime.UnallowedExceptionThrownError at JobScriptsSpec.groovy:24
Caused by: javaposse.jobdsl.dsl.DslException at JobScriptsSpec.groovy:21
Caused by: org.codehaus.groovy.control.MultipleCompilationErrorsException at JobScriptsSpec.groovy:21
How can I avoid the same?
Am I using the correct format?
Thanks in advance.
The new syntax uses the pipelineTriggers directive under the properties directive instead of the deprecated triggers directive:
pipelineJob('MyPipelineJob') {
properties {
pipelineTriggers {
triggers {
cron{
spec("TZ=Asia/Calcutta\n0 0 * * *")
}
}
}
}
}
The documentation for the pipelineTriggers is available in your own Jenkins server in the following URL:
https://your.jenkins.domain/plugin/job-dsl/api-viewer/index.html#path/javaposse.jobdsl.dsl.DslFactory.pipelineJob-properties-pipelineTriggers

Grails Scheduled Quartz Job never runs

Here is the Code:
class FollowUpJobOne {
FollowUpMailService followUpMailService;
static triggers = {
cron name: 'jobOneForFollowUp', cronExpression: "00 00 6 ? * *" //6 AM everyday as per server time
}
def execute() {
log.debug("control in Follow up job");
followUpMailService.sendFollowUpMails();
followUpMailService.sendFollowUpMailsForDandO();
}
}
*This Above Job never runs at 6 a.m.
I am unable to find the issue.
Please Help
Your class should ends with Job.
Just rename FollowUpJobOne to FollowUpOneJob
use grails create-job to create a job class which should be end with Job
cronExpression use 0 0 6 * * ?. Not sure whether quartz can parse 00.
confirm autoStartup = true

Grails multiple trigger with identifier for CRON

I have a simple Grails application which has a cron job. I have a requirement where I need to have two triggers for this crob job and In the execute method, according to which trigger, I would get information from different source. I have outlined what I need to do in the below code.
class sampleCronJob {
static triggers = {
cron name: 'trigger1' , cronExpression: "0 15 10 1 * ?"
cron name: 'trigger2' , cronExpression: "0 45 10 1 * ?"
}
def execute() {
def info
if(name=='trigger1'){
info = sampleService.getInfoFromTable1()
} else {
info = sampleService.getInfoFromTable2()
}
//process info
}
}
}
Is there a way to do this, where I need to get the name of the trigger, and have two triggers in this format?
Thanks in advance

Groovy Script - Logback configuration unawaited behaviour

I want to use Logback as my logging framework within Grails. therefore I set up everything in place to work but my implementation fails on the configuration file itself. the reason is, as I guess, somewhere whithin the scoping of Groovy Script but I'm not able to figure it out...
if I define my String properties without any identifier which I want to use later I get a warning that it may not be accessed. For example:
LOG_DIR = 'c:/temp/myproject/logs/'
BACKUP_DIR = LOG_DIR + 'backup/'
appender('F_MAIN', RollingFileAppender) {
file = LOG_DIR + 'test.log'
rollingPolicy(FixedWindowRollingPolicy) {
fileNamePattern = BACKUP_DIR + 'test.%d{yyyy-MM-dd}.%i.log.zip'
// .... and so on
}
}
I get the following error message from Logback, which I'm pretty sure is indicating that both LOG_DIR and BACKUP_DIR can not be reached:
13:33:32,036 |-ERROR in ch.qos.logback.classic.gaffer.AppenderDelegate#6fd00b - Appender [F_MAIN] of type [ch.qos.logback.core.rolling.RollingFileAppender] has no appplicable [LOG_DIR] property
13:33:32,068 |-ERROR in ch.qos.logback.classic.gaffer.ComponentDelegate#788ac3 - Component of type [ch.qos.logback.core.rolling.FixedWindowRollingPolicy] has no appplicable [BACKUP_DIR] property
I also tried the following approach by declaring both variables with the #Field tag, but it still does not work:
#Field String LOG_DIR = 'c:/temp/myproject/logs/'
#Field String BACKUP_DIR = LOG_DIR + 'backup/'
appender('F_MAIN', RollingFileAppender) {
file = LOG_DIR + 'test.log'
rollingPolicy(FixedWindowRollingPolicy) {
fileNamePattern = BACKUP_DIR + 'test.%d{yyyy-MM-dd}.%i.log.zip'
// .... and so on
}
}
what am I doing wrong here?
oh my!
after searching and a lot of trial/error I found the solution and it was so close and definitely seems obvious now: I had to declare both variables with def, so now they are visible throughout the whole script ;)
For example, this is working code:
def LOG_DIR = 'c:/temp/myproject/logs/'
def BACKUP_DIR = LOG_DIR + 'backup/'
appender('F_MAIN', RollingFileAppender) {
file = LOG_DIR + 'test.log'
rollingPolicy(FixedWindowRollingPolicy) {
fileNamePattern = BACKUP_DIR + 'test.%d{yyyy-MM-dd}.%i.log.zip'
// .... and so on
}
}
now, I'm also able to use a function like this within my script:
def createFilename(String directory, String name, boolean isBackupFile) {
String filename = ''
if(isBackupFile) {
filename = "${directory}backup/MyProject-${name}.%d{yyyy-MM-dd}.%i.log.zip"
} else {
filename = "${directory}MyProject-${name}.log"
}
return filename
}
def fileAppenderLog = createFilename(LOG_DIR, 'output', false)
def fileAppenderLogBackup = createFilename(LOG_DIR, 'output', true)
appender('F_MAIN', RollingFileAppender) {
file = fileAppenderLog
rollingPoliciy(FixedWindowRollingPolicy) {
fileNamePattern = fileAppenderLogBackup
// .... and so on
}
}
which is pretty useful, I think :), especially if you want to declare a bunch of different logfiles and even if you want to declare temporary logfiles which are created when Logback is rescanning this file ...

How do I completely bootstrap a grails environment?

I have the included grails script that I found in some random place on the internet and it works pretty well for firing up scripts in a bootstrapped grails env. The only thing it doesn't seem to do is kick off my conf/*Bootstrap.groovy scripts like when I do run-app.
Is there another function like loadApp() and configureApp() that will do that for me?
import org.codehaus.groovy.grails.support.PersistenceContextInterceptor
Ant.property(environment: "env")
grailsHome = Ant.antProject.properties."env.GRAILS_HOME"
includeTargets << new File("${grailsHome}/scripts/Bootstrap.groovy")
target('default': "Runs scripts in the test/local directory") {
if (!args) { throw new RuntimeException("[fail] This script requires an argument - the script to run.") }
depends(configureProxy, packageApp, classpath)
classLoader = new URLClassLoader([classesDir.toURI().toURL()] as URL[], rootLoader)
Thread.currentThread().setContextClassLoader(classLoader)
loadApp()
configureApp()
def interceptor = null
def beanNames = appCtx.getBeanNamesForType(PersistenceContextInterceptor)
if (beanNames && beanNames.size() == 1) {
interceptor = appCtx.getBean(beanNames[0])
}
try {
interceptor?.init()
new GroovyScriptEngine(Ant.antProject.properties."base.dir", classLoader).run("scripts/${args}.groovy", new Binding(['appCtx':appCtx]))
interceptor?.flush()
} catch (Exception e) {
e.printStackTrace()
interceptor?.clear()
} finally {
interceptor?.destroy()
}
}
Yes, try
new BootStrap().init()

Resources