ScheduledExecutorService继承自ExcutorService,也就是它是一种线程池,它不仅能实现任务的跟踪与管理,还能定时、定频执行任务。
文档渣翻
- An ExecutorService that can schedule commands to run after a given delay, or to execute periodically.
它是一种可以任务调度的线程池,你可以使其延时、或者定频执行。
- The schedule methods create tasks with various delays and return a task object that can be used to cancel or check execution. The scheduleAtFixedRate and scheduleWithFixedDelay methods create and execute tasks that run periodically until cancelled.
你可以指定任意的延迟来使用schedule方法以创建一个任务,它会返回一个task对象用以取消或者跟踪执行情况。scheduleAtFixedRate、scheduleWithFixedDelay 方法可以创建一个定频任务,直到你取消它。
- Commands submitted using the Executor.execute(Runnable) and ExecutorService submit methods are scheduled with a requested delay of zero. Zero and negative delays (but not periods) are also allowed in schedule methods, and are treated as requests for immediate execution.
你可以使用execute方法或者submit方法来提交一个任务,任务会被零延迟地立刻执行。你可以在schedule方法,也就是创建任务时指定零延迟或者负延迟,它们会被当作立即执行的任务。
- All schedule methods accept relative delays and periods as arguments, not absolute times or dates. It is a simple matter to transform an absolute time represented as a java.util.Date to the required form. For example, to schedule at a certain future date, you can use: schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS). Beware however that expiration of a relative delay need not coincide with the current Date at which the task is enabled due to network time synchronization protocols, clock drift, or other factors.
所有的schedule方法都可以接收 延迟 和 定频 作为参数,参数不是一个绝对的时间或者日期。将一个绝对的时间转换为需要的形式是很容易实现的。比方说,要实现未来某个时刻的任务调度,我们可以调用
schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS)
但要注意,这个延迟到期时,可能因为各种原因,例如网络时间同步协议、时间不同步等等、导致真正的延迟时间和你设定的不一致。(比如说现在是9点,我设置了10点.getTime() - System.currentTimeMillis()的delay,这时候服务器上的时间是9点50分,任务延迟10分钟就会执行,而不是预想的一小时。)
- The Executors class provides convenient factory methods for the ScheduledExecutorService implementations provided in this package.
在这个包中,Executors这个类提供了很多方便的Factory方法实现了ScheduledExecutorService,比如说: