Shady Ahmed Abdelaal
Shady Ahmed Abdelaal

Reputation: 51

Implemeting an Interrupt Service Routine in Java

i am building an app that connects to a router, get some data and inserts the acquired data into a database.

I need to get that data from the router each 30 seconds. And come back to update the Database with the newly acquired data.

I don't know how to implement that timer mechanism (it is similar to the interrupt service routine mechanism).

I am new to Java, Any Help ? Should i use a thread? I read briefly about threads but don't know exactly how they work.

EDIT: Please note that I have other thing to do in the main . The main is executing several functions. however, every 30 seconds i want to execute a single additional function.

Upvotes: 0

Views: 395

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533820

As you need to run other code you can do

ScheduleExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(new Runnable() {
    public void run() {
        Data data = getDataFromRouter();
        updateDatabase(data);
    }
}, 0, 30, TimeUnit.SECONDS);

Other wise I would have a simple loop like this.

while(true) {
    Data data = getDataFromRouter();
    updateDatabase(data);
    Thread.sleep(30 * 1000);
}

You need at least one thread, but you start with one.

Upvotes: 2

Guillaume
Guillaume

Reputation: 5553

The cleaner way is to schedule a periodic task.

You can use different APIs:

  • ScheduledExecutorService.scheduleAtFixedRate(...)
  • Timer.scheduleAtFixedRate(..)

Both will execute your code at periodic intervals.

Upvotes: 1

Related Questions