Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to call a function every 24 hours

Tags:

java

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?

like image 211
Ted pottel Avatar asked Oct 13 '15 14:10

Ted pottel


2 Answers

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);
like image 111
Tunaki Avatar answered Oct 05 '22 23:10

Tunaki


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.

like image 42
Rahul Tripathi Avatar answered Oct 06 '22 00:10

Rahul Tripathi