buzzsawddog
buzzsawddog

Reputation: 662

Grails scheduling a task without plugins

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?

Upvotes: 2

Views: 4851

Answers (4)

Martin Vlk
Martin Vlk

Reputation: 133

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.

Upvotes: 5

D&#243;nal
D&#243;nal

Reputation: 187399

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)

Upvotes: 2

Joshua Moore
Joshua Moore

Reputation: 24776

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!

Upvotes: 5

buzzsawddog
buzzsawddog

Reputation: 662

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.

Upvotes: 5

Related Questions