Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheduled Task using ExecutorService

I would like to use ExecutorService in JAVA to schedule the insertion into database every 5 min. this the task that i want to execute it:

    MyClass{
     a counter that count a handled data received from a Thread
     I receive usually 300 data line/second
     Apply a treatment on these data and keep the results in the memory

    every five minutes {
               update the database with the counters saved in memory*
      }
}

Basically it's calling the task each time he get a data from thread running in the background. and as i have more then 300 data/sec it's impossible to use it in this way.

So what i am trying to do id to handle the received tasks and keep a counter in the memory and update the database only each 5 min.

My question, is it possible to use these java function ScheduledExecutorService to do this, and how can we do it ( i don't want to block my JAVA application on the task for 5min, i want that that application run normally but without executing the task every time, i appreciate if you can show me an example of usage for these function ?

like image 642
Ahmadhc Avatar asked Feb 14 '23 22:02

Ahmadhc


1 Answers

ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
service.scheduleAtFixedRate(command, 5, 5, TimeUnit.MINUTES);

Where command is:

Runnable command = new Runnable() {
   public void run() {
      // update database
   }
}
like image 160
Bozho Avatar answered Mar 04 '23 02:03

Bozho