Faseela Thayattuchira
Faseela Thayattuchira

Reputation: 527

How to ensure that updating to database on certain interval

I am working in a application Spring java8 I have one function that generate Labels(pdf generation) asynchronously. it contains a loop, usually it will run more than 1000, it generate more than 1000 pdf labels. after every loop ends we need to update the database, so that we just saving the status, ie initially it save numberOfgeneratedCount=0 , after each label we just increment the variable and update the table. It is not Necessary to save this incremented count to db at every loop ends, what we need is in a fixed intervals only we need to update the database to reduce load on dataBase inserts. currently my code is like

// Label is a database model class labeldb is variable of that 
//commonDao.saveLabelToDb function to save Label object

int numberOfgeneratedCount =0;
labeldb.setProcessedOrderCount(numberOfgeneratedCount);
commonDao.saveLabelToDb(labeldb);

for(Order order: orders){
  generated = true;
  try{
        // pdf generation code
     }catch Exception e{
        // catch block here
        generated = false;
     }

     if(generated){
          numberOfgeneratedCount++;
          deliveryLabeldb.setProcessedOrderCount(numberOfgeneratedCount);
          commonDao.saveLabelToDb(labeldb );
     }
}

to improve the performance we need to update database only an interval of 10 seconds. Any help would appreciated

Upvotes: 2

Views: 106

Answers (1)

Faseela Thayattuchira
Faseela Thayattuchira

Reputation: 527

I have done this using the following code, I am not sure about whether this is a good solution, Some one please improve this using some built in functions

int numberOfgeneratedCount =0;
labeldb.setProcessedOrderCount(numberOfgeneratedCount);
commonDao.saveLabelToDb(labeldb);
int nowSecs =LocalTime.now().toSecondOfDay();
int lastSecs = nowSecs;

for(Order order: orders){
  nowSecs = LocalTime.now().toSecondOfDay();
  generated = true;
  try{
        // pdf generation code
     }catch Exception e{
        // catch block here
        generated = false;
     }

     if(generated){
          numberOfgeneratedCount++;
          deliveryLabeldb.setProcessedOrderCount(numberOfgeneratedCount);
          if(nowSecs-lastSecs > 10){
                lastSecs=nowSecs;
                commonDao.saveLabelToDb(labeldb );
             }
        
     }
}

Upvotes: 1

Related Questions