Run java thread at specific times

前端 未结 3 827
孤城傲影
孤城傲影 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);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-19 06:55

    TimerTask handles this case.

    See schedule(TimerTask, Date)

    If you don't want to have to keep scheduling the jobs, you may want to look into a job scheduling tool like Quartz.

    0 讨论(0)
  • 2020-12-19 07:00

    Quartz would be a good fit since you're application is web-based. It will provide the fine-grained time based scheduling you need.

    Quartz is a full-featured, open source job scheduling service that can be integrated with, or used along side virtually any Java EE or Java SE application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components that may executed virtually anything you may program them to do. The Quartz Scheduler includes many enterprise-class features, such as JTA transactions and clustering.

    0 讨论(0)
提交回复
热议问题