Run java thread at specific times

前端 未结 3 826
孤城傲影
孤城傲影 2020-12-19 06:29

I have a web application that synchronizes with a central database four times per hour. The process usually takes 2 minutes. I would like to run this process as a thread a

3条回答
  •  [愿得一人]
    2020-12-19 06:36

    You can let the Runnable schedule its "next run".

    Such as,

    class Task implements Runnable {
        private final ScheduledExecutorService service;
    
        public Task(ScheduledExecutorService service){
            this.service = service;
        }
    
        public void run(){
            try{
                 //do stuff
            }finally{
                //Prevent this task from stalling due to RuntimeExceptions.
                long untilNextInvocation = //calculate how many ms to next launch
                service.schedule(new Task(service),untilNextInvocation,TimeUnit.MILLISECONDS);
            }
        }
    }
    

提交回复
热议问题