Question

For one of our applications we have a different Tasks that we would like to happen on a scheduled basis. However we don't want to bother with quartz for several different reasons.

In grails, how do we go about scheduling a task that can run on a regular basis?

Was it helpful?

Solution

After researching for quite some time we came to this conclusion:

Within the Groovy Source Packages we created an interface

interface Task{
  void executeTask()
}

Next we created our Task:

class SayHelloTask implements Task{
    void executeTask(){
    println "Hello"
  }
}

Within the resources.groovy file we added the following:

import package.SayHelloTask
beans = {
  sayHelloTask(SayHelloTask){
  }

  xmlns task: "http://www.springframework.org/schema/task"

  task.'scheduled-tasks'{
    task.scheduled(ref:'retryEmailTask', method: 'executeTask', cron: '0-59 * * * * *')
  }
}

We went with this solution because it cut the overhead of Quartz. It matches how we do things in our Java projects.

OTHER TIPS

I prefer using the annotations on my services when dealing with Spring based scheduled tasks.

grails-app/conf/spring/resrouces.groovy

beans {
    xmlns task: "http://www.springframework.org/schema/task"
    task.'annotation-driven'('proxy-target-class': true)
}

Then on my service:

class MyService {
  @Scheduled(cron="*/5 * * * * MON-FRI")
  void doSomething() {
    ...    
  }
}

Regardless of how you do this, be cautious about your Hibernate session scope. Good luck!

For the records, as of Grails 3.2.10 this can be achieved neatly by using annotations the following way.

Create an ordinary Grails service:

class ScheduledService {
  boolean lazyInit = false    // <--- this is important

  @Scheduled(fixedRate = 20000L)
  def myBusinessMethodForTheJob() {
    log.info 'Executing scheduled job...'
  }
}

Enable scheduling in the application:

@EnableScheduling
class Application extends GrailsAutoConfiguration {
    static void main(String[] args) {
        GrailsApp.run(Application, args)
    }
}

Done.

Another option is the Timer and TimerTask classes provided by the JDK. You can run this example in the Groovy console to see it in action

def task = new TimerTask() {

  void run() {
    println "task running at ${new Date()}"
  }
}

def firstExecutionDelay = 1000
def delayBetweenExecutions = 2000

new Timer(true).schedule(task, firstExecutionDelay, delayBetweenExecutions)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top