简体   繁体   中英

Sending 15 records as api request in every one second absolutely with Java

I would like to know how to send multiple request to other api and update response status to our database every one second , let sending request is TPS = 15. I used both Timer and ScheduleExecutorService as below. But both did not support by sending 15 requests in every 1 second periodically. Sometimes it works well requests = 15 in every one second . And sometimes only requests = 13 in 11:04:01 and requests = 17 in 11:04:02. By seeing seconds, in 11:04:01 I want to send is 15 records, actually it sent 13 records, difference is 2 records. so, another 11:04:02 , remaining 2 records reached to this second and total records become 15+2 = 17 records. So, Please help me to solve this issue and which technology or library should I use rather than both Timer and ScheduledExecutorService.

Timer timer = new Timer();
timer.schedule(new sendRequest(), 0, 1000);

/////////////////////////////////////////////

ScheduledExecutorService executor =
Executors.newSingleThreadScheduledExecutor();

Runnable periodicTask = new Runnable() {
public void run() {
    // Invoke method(s) to do the work
    doPeriodicWork();
}
};

executor.scheduleAtFixedRate(periodicTask, 0, 1, TimeUnit.SECONDS);

This is attachment log file screenshot. mismatch and merge records in next second log screenshot in each second

public class SendTPS extends TimerTask {

  public static void main(String[] args){

    int maxTPS = 15;

    Timer timer = new Timer();
    int maxSleepInterval = Math.round((1000 / maxTPS));

    timer.schedule(new SendTPS(), 0, maxSleepInterval);
  }

  public static  void fetchData(){
    System.out.println(new SimpleDateFormat("HH:mm:ss").format(new 
    java.util.Date())+"fetch data....");
  }

  public void run() {
    fetchData();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM