I'm trying to get a function to be called every day. Right now my code is as follows:
do {
Thread.sleep(1000*60*60*24);
readInFile();
} while (true);
The issue is that it is being called every day plus the time it takes to execute the function readInFile
. Is there a way to do a callback or something to go off every 24 hours?
You can use ScheduledExecutorService.scheduleAtFixedRate
method to invoke a Runnable
at a fixed rate.
Sample code to invoke a runnable every day (with no initial delay):
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(myRunnable, 0, 1, TimeUnit.DAYS);
You can try this:
Timer timer = new Timer ();
TimerTask t = new TimerTask () {
@Override
public void run () {
// some code
}
};
timer.schedule (t, 0l, 1000*60*60*24);
or else you can use the ScheduledExecutorService
An ExecutorService that can schedule commands to run after a given delay, or to execute periodically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With