问题
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 ?
回答1:
ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
service.scheduleAtFixedRate(command, 5, 5, TimeUnit.MINUTES);
Where command
is:
Runnable command = new Runnable() {
public void run() {
// update database
}
}
来源:https://stackoverflow.com/questions/19489781/scheduled-task-using-executorservice