Worker Thread in Java

后端 未结 4 2162
天命终不由人
天命终不由人 2021-02-08 07:13

I need to read the data from a table every minute through thread & then perform certain action.

Should I just start a thread & put it in sleep mode for 1 minute

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-08 07:46

    An alternative to create a thread yourself is to use the ExcecutorService, where Executors.newScheduledThreadPool( 1 ) creates a thred pool of size 1 and scheduleAtFixedRate has the signature: scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);

    public class ScheduledDBPoll
    {
      public static void main( String[] args )
      {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool( 1 );
        ScheduledFuture sf = scheduler.scheduleAtFixedRate(
            new Runnable() {
              public void run() {
                pollDB();
              }
            },
            1,  60,TimeUnit.SECONDS );
      }
    }
    

提交回复
热议问题