Question

I'm currently having issues with a ScheduledExecutorService executing faster than the given timeframe.

scheduleAtFixedRate states that subsequent executions may be late but it does not wait the given time afterwords.

GrabPutTask simply grabs information from a source, assigns the capture time, and sends it to a database. Because the interval becomes less than a second, the database entry gives an error in regards to a duplicate entry.

Is there a way to execute the task at a fixed time AFTER the previous task has completed?

I've read here that the tasks "bunch up" in a queue but a solution for my needs was not presented.

private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

public static void main(String[] args)
{
    //
    ..
    //
    //Creating the looping thread.
    try
    {
        scheduler.scheduleAtFixedRate(new GrabPutTask(), (long) 1, (long) (seconds * 1000), TimeUnit.MILLISECONDS);
        LOGGER.info(String.format("DBUpdater connected and running. (GetAddr: %s, SetAddr: %s, Poll Rate: %.2f, Sector Number: %s, Number of PLCs: %d)",
                                  FROM_IP.split(":", 2)[0] + ":" + fromServer.getPort(), dataSource.getURL(), seconds, SECTOR, NUMBER_OF_PLCS_ON_MASTER));
    }
    catch (IllegalArgumentException ex)
    {
        LOGGER.log(Level.SEVERE, null, ex);
        printUsage();
        System.exit(1);
    }
}

Example execution time intervals:

Event Called: 2014/02/12 14:19:07.199
Event Called: 2014/02/12 14:19:08.199
Event Called: 2014/02/12 14:19:09.199
Event Called: 2014/02/12 14:19:10.199
Event Called: 2014/02/12 14:19:11.199
Event Called: 2014/02/12 14:19:12.199
Event Called: 2014/02/12 14:19:13.199
Event Called: 2014/02/12 14:19:14.199
Event Called: 2014/02/12 14:19:15.199
Event Called: 2014/02/12 14:19:16.199
Event Called: 2014/02/12 14:19:17.199
Event Called: 2014/02/12 14:19:18.199
...
Event Called: 2014/02/12 14:20:21.415 (A load on the server it seems)
Event Called: 2014/02/12 14:20:22.215
Event Called: 2014/02/12 14:20:23.425
Event Called: 2014/02/12 14:20:24.422
Event Called: 2014/02/12 14:20:25.276
Event Called: 2014/02/12 14:20:25.997

No correct solution

OTHER TIPS

scheduleWithFixedRate tries to "catch up" if execution is delayed for whatever reason. You can use scheduleWithFixedDelay to keep the system from starting the clock until after the previous execution; delays will accumulate and won't catch up.

To sleep for any amount of time.

try {
    Thread.sleep(someTime);
} catch(InterruptedException ex) {
    Thread.currentThread().interrupt();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top