Continuously poll a REST service in Grails

2019-06-24 12:13发布

问题:

I am creating a web app in Grails and I would like to continuously (every 5 minutes or so) poll a REST service using GET, which retrieves a series of messages (or possibly none, it depends) and once it is donde, my application should save the retrieved data as an object and store it in my database. The problem is that I have no idea how I should implement it (with a cron job using Quartz?)

回答1:

A cron job using quartz would be really easy to implement. The quartz plugin is very easy to use (just install it and then "grails create-job Foo"). Inside the task, you can use a cron expression (or a number of other ways) that will cause the job to get executed based on the schedule.

Depending on a few things, the GET expression is also very easy to write. Depending on the service you're trying to hit it could be as easy as:

def result = new URL("http://google.com").text
// parse result depending on what it is


回答2:

using the Quartz plugin and make a cron job out of it is probably the best way forward, especially if you are going to need other pollers.

However, if you know its a once off, and you dont want to pull in quartz (for some odd reason), you can still roll your own poller using a timer task, or even use a groovy thread:

Thread.start {
   while (keepGoing) {
      def result = new URL("http://google.com").text
      // parse result depending on what it is
      //perhaps def model = new YourDomainModel(result).save()
      keepGoing = model.shouldContinue //calculate whether to keep going based on the result, or some other method call/logic
      Thread.sleep(5*60*1000) //min*seconds_per_min*milliseconds_per_second
   }
}

You can then call this during bootStrap, or create a service class, call the above inside the constructor, and have a method to stop the thread (but if you get to this stage, its really just easier to use quartz).



标签: rest grails