Running a Java Thread in intervals

后端 未结 3 542
-上瘾入骨i
-上瘾入骨i 2020-12-04 16:34

I have a thread that needs to be executed every 10 seconds. This thread contains several calls (12 - 15) to a database on another server. Additionally, it also accesses arou

3条回答
  •  -上瘾入骨i
    2020-12-04 16:44

    I find that a ScheduledExecutorService is an excellent way to do this. It is arguably slightly more complex than a Timer, but gives more flexibility in exchange (e.g. you could choose to use a single thread or a thread pool; it takes units other than solely milliseconds).

    ScheduledExecutorService executor =
        Executors.newSingleThreadScheduledExecutor();
    
    Runnable periodicTask = new Runnable() {
        public void run() {
            // Invoke method(s) to do the work
            doPeriodicWork();
        }
    };
    
    executor.scheduleAtFixedRate(periodicTask, 0, 10, TimeUnit.SECONDS);
    

提交回复
热议问题