Scheduled Executor Service

本文介绍如何使用ScheduledExecutorService创建并运行周期性的任务。通过示例代码展示了如何设置任务立即启动,并每隔10秒执行一次,同时设置了一个一小时后的停止任务。

Executor can return Executor, ExecutorService, and ScheduledExecutorService.

This is very, very usful Tiger new timer.

 

scheduler.scheduleAtFixedRate(new TimePrinter(System.out), 0, 10, SECONDS);

4 arguments:

1) Runable or Callable, which is the task scheduled to run.

2) 0. When the first time to run. 0 seconds later, means, immediately.

3) 10. When next time run. 10 seconds later.

4) What's time unit. The argument 0, and 10, all use the time unit SECONDs.

 

 

package test;

 

import java.io.PrintStream;

import java.util.Date;

import java.util.concurrent.Executors;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.ScheduledFuture;

import static java.util.concurrent.TimeUnit.SECONDS;;

 

public class Thread5

{

      public static void main(String[] args)

      {

 

            // Get the scheduler

            //An alternative way to get scheduler is like this, you can simply replace with it

            //ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(10);

            ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

 

            // Get a handle, starting now, with a 10 second delay

            final ScheduledFuture<?> timeHandle = scheduler.scheduleAtFixedRate(new TimePrinter(System.out), 0, 10, SECONDS);

 

            // Schedule the event, and run for 1 hour (60 * 60 seconds)

            scheduler.schedule(new Runnable()

            {

                  public void run()

                  {

                        timeHandle.cancel(false);

                  }

            }, 60 * 60, SECONDS);

 

      }//end of main

}

 

class TimePrinter implements Runnable

{

      private PrintStream out;

 

      public TimePrinter(PrintStream out)

      {

            this.out = out;

            System.out.println("a TimePrinter instance is created");

      }

 

      public void run()

      {

            out.printf("Current time: %tr%n", new Date());

      }

}

 

 

 

 

 

 

 

 

Summary:

 

Step 1) Get a ScheduledExecutorService --- Scheduler
Step 2) Tell the scheduler, which to run, how frequent, when to start. ---generate ScheduledFuture
Step 3) Start the Scheduler using schedule() method, wraping ScheduledFuture into Runnable, passing the Runnable to the schedule()

 

 

 

### JavaScheduledExecutorService 的示例与最佳实践 #### 使用 ScheduledExecutorService 执行定时任务 `ScheduledExecutorService` 是 `java.util.concurrent` 包中的接口,用于执行延迟或周期性的任务。此接口提供了灵活的方法来安排命令的异步执行[^1]。 下面是一个简单的例子展示如何创建并使用 `ScheduledExecutorService` 来定期运行一个任务: ```java import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class SchedulerExample { private static final int CORE_POOL_SIZE = 2; public static void main(String[] args) throws InterruptedException { // 创建一个具有固定线程数的核心池大小为2的调度器服务实例 try (ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(CORE_POOL_SIZE)) { Runnable task = () -> System.out.println("Task executed at " + System.currentTimeMillis()); // 安排task在初始延迟0秒后每两秒钟重复一次 scheduler.scheduleAtFixedRate(task, 0, 2, TimeUnit.SECONDS); // 让主线程等待一段时间以便观察计划的任务输出 Thread.sleep(10_000); // 停止接收新任务,并尝试停止正在处理的任务 scheduler.shutdownNow(); } } } ``` #### 最佳实践建议 为了确保应用程序稳定性和性能,在使用 `ScheduledExecutorService` 时应遵循一些指导原则: - **正确处理中断信号**:当调用 `shutdown()` 或者 `shutdownNow()` 方法请求关闭 Executor Service 实例时,应该适当地响应这些操作发出给工作线程的中断信号。 - **避免捕获未定义的行为异常**:不应捕捉像 `NullPointerException` 和 `IndexOutOfBoundsException` 这样的运行时异常;相反地,尽可能提前检查可能引发这些问题的情况[^2]。 - **注意线程安全问题**:如果多个线程可能会访问共享资源,则需特别小心以防止数据竞争条件的发生。例如,在多线程环境中使用日期工具类 (`DateUtils`) 应该关注其线程安全性[^3]。 通过以上方法可以有效地利用 `ScheduledExecutorService` 接口实现高效可靠的并发编程解决方案。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值