2

I am planning on building a webservice client that always checks for some records in the database and performs certain decisions based on results of the database content at each moment in time.

So i was thinking, how could i make the client run always ?

The only thing that came into my mind is to have an endless loop. Something like :

public static void main(String[] args)
{
  while(true)
  {
     //Do database operation.
  }
}

So is this the right way of doing something like what i explained ?

  • You should read about java threads: http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html – 0x9BD0 Apr 08 '14 at 16:16
  • whoy not use scheduler http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ScheduledExecutorService.html ? – user902383 Apr 08 '14 at 16:19
  • Would running at a specified schedule suit this use case? More info here - http://stackoverflow.com/questions/7814089/how-to-schedule-a-periodic-task-in-java – Matthew Wilson Apr 08 '14 at 16:19
  • A Timer would be nicer. Check (empirically) what the update interval is for data base queries. Inspect the sent headers for times. – Joop Eggen Apr 08 '14 at 16:20

3 Answers3

3

Sounds like a perfect use case for a scheduler, then you will be able to control your refresh ratio. Read How to schedule a periodic task in Java? for your options.

Community
  • 1
  • 1
Norbert Radyk
  • 2,608
  • 20
  • 24
0

There is not much wrong in this, just add a Thread.sleep(milliseconds) value in your loop for a breather. otherwise you could probably look at a light scheduler which could call the method at regular intervals.

Sambhav Sharma
  • 5,741
  • 9
  • 53
  • 95
0

The use of an infinite loop on a server isn't necessarily a bad idea. It's prevalent in tutorials that explain writing servers. Typically, I don't tend to put this in my main method, but rather encapsulate it in a separate thread. I also typically don't use true, but some variable that can be toggled so that on some action (a message from a client, a key press, GUI actions, etc.), I can set that variable to false to stop execution of the server.

However, you may want to look at other concurrency options, such as pausing execution of threads so you aren't always performing the action or the Executor interfaces for managing threads (especially the Scheduled Execution facilities).

Thomas Owens
  • 114,398
  • 98
  • 311
  • 431