ScheduledExecutorService定时周期执行指定的任务

转载来自:http://blog.csdn.net/tsyj810883979/article/details/8481621


1.   ScheduleExecutorService接口中有四个重要的方法,其中scheduleAtFixedRate和scheduleWithFixedDelay在实现定时程序时比较方便。

下面是该接口的原型定义

java.util.concurrent.ScheduleExecutorService extends ExecutorService extends Executor


接口scheduleAtFixedRate原型定义及参数说明

  1. public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,  
  2.             long initialDelay,  
  3.             long period,  
  4.             TimeUnit unit);  

command:执行线程
initialDelay:初始化延时
period:两次开始执行最小间隔时间
unit:计时单位

接口scheduleWithFixedDelay原型定义及参数说明

  1. public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,  
  2.                 long initialDelay,  
  3.                 long delay,  
  4.                 TimeUnit unit);  

command:执行线程
initialDelay:初始化延时
period:前一次执行结束到下一次执行开始的间隔时间(间隔执行延迟时间)
unit:计时单位

二:功能示例

1.按指定频率周期执行某个任务。

初始化延迟0ms开始执行,每隔100ms重新执行一次任务。

  1. /** 
  2.  * 以固定周期频率执行任务 
  3.  */  
  4. public static void executeFixedRate() {  
  5.     ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
  6.     executor.scheduleAtFixedRate(  
  7.             new EchoServer(),  
  8.             0,  
  9.             100,  
  10.             TimeUnit.MILLISECONDS);  
  11. }  
间隔指的是连续两次任务开始执行的间隔。

2.按指定频率间隔执行某个任务。

初始化时延时0ms开始执行,本次执行结束后延迟100ms开始下次执行。

  1. /** 
  2.  * 以固定延迟时间进行执行 
  3.  * 本次任务执行完成后,需要延迟设定的延迟时间,才会执行新的任务 
  4.  */  
  5. public static void executeFixedDelay() {  
  6.     ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
  7.     executor.scheduleWithFixedDelay(  
  8.             new EchoServer(),  
  9.             0,  
  10.             100,  
  11.             TimeUnit.MILLISECONDS);  
  12. }  

3.周期定时执行某个任务。

有时候我们希望一个任务被安排在凌晨3点(访问较少时)周期性的执行一个比较耗费资源的任务,可以使用下面方法设定每天在固定时间执行一次任务。

  1. /** 
  2.  * 每天晚上8点执行一次 
  3.  * 每天定时安排任务进行执行 
  4.  */  
  5. public static void executeEightAtNightPerDay() {  
  6.     ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
  7.     long oneDay = 24 * 60 * 60 * 1000;  
  8.     long initDelay  = getTimeMillis("20:00:00") - System.currentTimeMillis();  
  9.     initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;  
  10.   
  11.     executor.scheduleAtFixedRate(  
  12.             new EchoServer(),  
  13.             initDelay,  
  14.             oneDay,  
  15.             TimeUnit.MILLISECONDS);  
  16. }  
  1. /** 
  2.  * 获取指定时间对应的毫秒数 
  3.  * @param time "HH:mm:ss" 
  4.  * @return 
  5.  */  
  6. private static long getTimeMillis(String time) {  
  7.     try {  
  8.         DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");  
  9.         DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");  
  10.         Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);  
  11.         return curDate.getTime();  
  12.     } catch (ParseException e) {  
  13.         e.printStackTrace();  
  14.     }  
  15.     return 0;  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`ScheduledExecutorService` 是 Java 中的一个工具类,用于在给定的时间间隔或延迟后执行任务。在 Java 中,你可以使用 `ScheduledThreadPoolExecutor` 或 `Executors` 类中的静态工厂方法来创建一个 `ScheduledExecutorService`。 以下是一个简单的例子,说明如何在晚上1点(假设是协调世界时间的23:00)定时执行一个任务: ```java import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ScheduledTaskExample { public static void main(String[] args) { // 创建一个ScheduledExecutorService ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); // 定义一个Runnable任务 Runnable task = () -> { System.out.println("Task executed at midnight"); }; // 使用ScheduledFuture来计划任务执行 ScheduledFuture<?> future = executor.scheduleAtFixedRate(task, 0, 1, TimeUnit.DAYS); // 延迟0秒开始,每1天执行一次 // 关闭线程池以确保所有任务完成后终止 // 当然,在实际应用中,你可能希望在程序结束时关闭它,或者在任务完成后优雅地关闭 executor.shutdown(); } } ``` 在这个例子中,`scheduleAtFixedRate` 方法接受四个参数: 1. 任务 (`task`):一个实现了 `Runnable` 或 `Callable` 接口的实例。 2. 初始延迟 (`0`):任务将在调用 `scheduleAtFixedRate` 后立即开始执行,这里是0秒。 3. 重复周期 (`1`, `TimeUnit.DAYS`):每1天执行一次任务。 4. 时间单位 (`TimeUnit.DAYS`):指定延迟和周期的时间单位。 注意,这个例子假设你的程序运行在24小时制环境中,如果使用的是其他时区或者非标准时间,你可能需要根据具体情况进行调整。此外,如果你的任务执行可能比较耗时,最好检查 `future.get()` 是否成功,以防止阻塞主线程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值