Attempting to call a function every 24 hours

I am trying to get a function that will be called every day. My code now looks like this:

do {
    Thread.sleep(1000*60*60*24);
    readInFile();
} while (true);

The problem is that it is called every day, plus the time it takes to complete the function readInFile. Is there a way to make a callback or something to go out every 24 hours?

+4
source share
4 answers

You can try the following:

Timer timer = new Timer ();
TimerTask t = new TimerTask () {
    @Override
    public void run () {
        // some code
    }
};

timer.schedule (t, 0l, 1000*60*60*24);

otherwise you can use ScheduledExecutorService

The ExecutorService service, which can schedule the execution of commands after a specified delay or periodic execution.

+3
source

ScheduledExecutorService.scheduleAtFixedRate Runnable .

runnable ( ):

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(myRunnable, 0, 1, TimeUnit.DAYS);
+6

You can use a scheduler such as Quartz or Spring to set the code to run once a day.

Spring http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html

http://spring.io/guides/gs/scheduling-tasks/

//1:01 am every day
@Scheduled(cron = "0 1 1 * * ?")
public void readDaily() {
  readInFile();
}

Quartz https://quartz-scheduler.org

JobDetail job = new JobDetail();
    job.setName("dummyJobName");
    job.setJobClass(HelloJob.class);

    //configure the scheduler time
    Trigger trigger = new CronTrigger("trigger1", "group1");
    trigger.setCronExpression("0 0 15 * * ?"); //3pm every day

    //schedule it
    Scheduler scheduler = new StdSchedulerFactory().getScheduler();
    scheduler.start();
    scheduler.scheduleJob(job, trigger);
+1
source

In the past, I did this using the Windows Task Scheduler and Unix cron tasks.

0
source

Source: https://habr.com/ru/post/1611451/


All Articles