Skip to content

Instantly share code, notes, and snippets.

@VenkataRaju
Last active August 12, 2017 10:44
Show Gist options
  • Save VenkataRaju/ada4c2779a8aa38fac54cbc9d78b0e8c to your computer and use it in GitHub Desktop.
Save VenkataRaju/ada4c2779a8aa38fac54cbc9d78b0e8c to your computer and use it in GitHub Desktop.
Skip the current iteration of the task if the previous iteration took more time than the expected time
public class DelayedTaskSkipTest
{
public static void main(String[] args) throws Throwable
{
long delayBetweenTaskIterationsInMillis = 2000;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
int i = 1;
@Override
public void run()
{
long delay = System.currentTimeMillis() - scheduledExecutionTime();
if (delay >= 100 /* MAX_TARDINESS */)
{
System.out.printf("%nSkipping the current iteration as it was delayed by %3d ms%n%n", delay);
return;
}
System.out.printf("%d Start %tT:%<tL%n", i, new Date());
try
{
Thread.sleep(delayBetweenTaskIterationsInMillis + 200);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.printf(" End %tT:%<tL%n", new Date());
if (i++ == 4)
timer.cancel();
}
}, 0 /* delay */, delayBetweenTaskIterationsInMillis);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment