java 执行定时任务

系统管理员 2022-06-04 07:42 439阅读 0赞

public static void main(String[] args) throws InterruptedException {
//启动了默认两个线程的线程池,调度两个周期性任务。
ScheduledExecutorService execService = Executors.newScheduledThreadPool(2);

  1. //在延时1秒后第一次执行任务,以后以5秒为周期再次执行任务。scheduleAtFixedRate拥有固定的执行周期,这里时5秒
  2. //第一个参数是任务,第二个参数是延时时间,第三个参数是执行周期,第四个参数是时间单位
  3. execService. **scheduleAtFixedRate**( **newRunnableInstance()**, 1, 5, TimeUnit.SECONDS);
  4. //即每次执行时间为:initialDelay, initialDelay+executeTime+delay, initialDelay+2\*executeTime+2\*delay;ScheduleWithFixedDelay 取决于每次任务执行的时间长短,是基于不固定时间间隔进行任务调度。
  5. //execService.scheduleWithFixedDelay(newRunnableInstance(), 1, 10, TimeUnit.SECONDS);
  6. //Thread.sleep(5000L);
  7. //execService.shutdown();
  8. \}

private static Runnable newRunnableInstance() {
return new Runnable(){
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+” -> “+System.currentTimeMillis()+” task execute!”);
}
};
}

发表评论

表情:
评论列表 (有 0 条评论,439人围观)

还没有评论,来说两句吧...

相关阅读