-->

Grails creating routines

2019-08-25 11:49发布

问题:

Let's say, i have a specific information in the database that needs to be sent for a specific user by email in a specific time of the day.

a) How can i create a routine in Grails, which is basically an action that is always running - without being associated with any event? Let's say, every hour that action is runned.

I was thinking about something like this:

while(true){

...
myCodeHere
...
wait 30minutes
}

Will this actually work? Without too much processing? And how can i have an action permanently running no matter what. I there is a specific way of doing this? Thanks in advanced, RR

回答1:

Avoiding quartz and plugins you may use pure Spring Framework

1) add to container

<task:annotation-driven executor="executor" scheduler="scheduler"/>
<task:executor id="executor" pool-size="5"/>
<task:scheduler id="scheduler" pool-size="10"/>

(do not forget to define task and tx namespaces)

2) Create some bean and add method

@Scheduled(fixedDelay=4000)
public void method() {
  // do something every 4 seconds
}

finish! For more info see spring framework



回答2:

The usual way to do this in a grails app is with the Quartz scheduler plugin. The plugin provides a simple cron-like DSL for scheduling jobs. For example, to run a job every 30 minutes, you could configure it like this:

class MyJob  {
    static cronExpression = "0 0/30 * * * ?"

    def execute(){ /* do something useful */ }
}

If you want to run a background thread all the time, take a look at the executor plugin which provides an ExecutorService wrapped up properly to get a hibernate session.