tags:

views:

52

answers:

2

Hi,

I have a timer class scheduled to execute every 5 mins. I want to start this timer class when tomcat starts up the first time. What would be the best approach to do this in Grails?

Thank You. Jay Chandran

+2  A: 

You can't start the timer class when Tomcat starts since it wouldn't have access to your Grails app with all the associated data it needs to execute. You can start it when your Grails app starts though by putting the necessary code in Conf/bootstrap.groovy

Jared
I put the logic using Timer in Config.groovy. My idea is to update a file every 5 mins. The problem I am facing is if I change my server time, the Timer no longer works and the file is no longer updated! http://bugs.sun.com/view_bug.do?bug_id=4290274I am also using timer.scheduleAtFixedRate method.I guess Quartz is better option.
Jay Chandran
+4  A: 

If you need more flexibility than just a timer, you can use the Quartz Plugin and configure a Cron Job:

class MyTimerJob {
    static triggers = {
        // cron trigger for every 5 minutes
        cron name: 'myCronTrigger', cronExpression: '0 */5 * * * ?'
    }

    def execute = {
        // perform task
    }
}

To start Quartz on application startup (like Jared said: not on tomcat startup), make sure your grails-app/conf/QuartzConfig.groovy has the following:

quartz {
    autoStartup = true
}

autoStartup = true is the default, so you probably won't need to change anything there.

Using this plugin will save you from having to handle the timer logic yourself.

Rob Hruska
Hi, I installed the Quartz plugin as you mentioned and tried using it. But using <pre><code>cron name: 'myCronTrigger', cronExpression: '0 */5 * * ?' </code></pre> in the static trigger caused my grails application to not start at all. So instead used <pre><code> simple name: 'mySimpleTrigger', startDelay: 60000, repeatInterval: 1000 </code></pre>Then the job works. Here also I am facing similar issue as Timer. If I change the system date, the Quartz job does not fire again. Am I missing something?
Jay Chandran
As for the first issue you mention, I notice the cron syntax is incorrect. I apologize - I had the wrong syntax in my example; I've updated it. I'm not sure if that would cause the app to not start, though. It's tough to know without seeing an error message. For the issue with changing the system time, I don't have a good suggestion.
Rob Hruska
Thanks for that. There was no error reported in the console which was strange!
Jay Chandran