Java Scheduler ScheduledExecutorService ScheduledThreadPoolExecutor示例

Welcome to the Java Scheduler Example. Today we will look into ScheduledExecutorService and it’s implementation class ScheduledThreadPoolExecutor example.

欢迎使用Java Scheduler示例。 今天,我们将研究ScheduledExecutorService及其实现类ScheduledThreadPoolExecutor示例。

Java Scheduler ScheduledExecutorService (Java Scheduler ScheduledExecutorService)

java scheduler, java scheduler example, ScheduledExecutorService, ScheduledThreadPoolExecutor

Sometimes we need to execute a task periodically or after specific delay. Java provides Timer Class through which we can achieve this but sometimes we need to run similar tasks in parallel. So creating multiple Timer objects will be an overhead to the system and it’s better to have a thread pool of scheduled tasks.


有时我们需要定期或在特定的延迟后执行任务。 Java提供了Timer类,通过它可以实现此目的,但有时我们需要并行运行类似的任务。 因此,创建多个Timer对象将是系统的开销,并且最好有一个计划任务的线程池。

Java provides scheduled thread pool implementation through ScheduledThreadPoolExecutor class that implements ScheduledExecutorService interface. ScheduledExecutorService defines the contract methods to schedule a task with different options.

Java通过实现ScheduledExecutorService接口的ScheduledThreadPoolExecutor类提供了调度线程池实现。 ScheduledExecutorService定义合同方法以安排具有不同选项的任务。

Sometime back I wrote a post about Java ThreadPoolExecutor where I was using Executors class to create the thread pool. Executors class also provide factory methods to create ScheduledThreadPoolExecutor where we can specify the number of threads in the pool.

有时,我写了一篇有关Java ThreadPoolExecutor的帖子,其中我使用Executors类创建线程池。 Executors类还提供了工厂方法来创建ScheduledThreadPoolExecutor ,我们可以在其中指定池中的线程数。

Java Scheduler示例 (Java Scheduler Example)

Let’s say we have a simple Runnable class like below.

假设我们有一个简单的Runnable类,如下所示。

WorkerThread.java

WorkerThread.java

package com.journaldev.threads;

import java.util.Date;

public class WorkerThread implements Runnable{

private String command;
    
    public WorkerThread(String s){
        this.command=s;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+" Start. Time = "+new Date());
        processCommand();
        System.out.println(Thread.currentThread().getName()+" End. Time = "+new Date());
    }

    private void processCommand() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString(){
        return this.command;
    }
}

It’s a simple Runnable class that takes around 5 seconds to execute its task.

这是一个简单的Runnable类,大约需要5秒钟来执行其任务。

Let’s see a simple example where we will schedule the worker thread to execute after 10 seconds delay. We will use Executors class newScheduledThreadPool(int corePoolSize) method that returns instance of ScheduledThreadPoolExecutor. Here is the code snippet from Executors class.

让我们看一个简单的示例,在该示例中,我们将调度工作线程在延迟10秒后执行。 我们将使用Executors类的newScheduledThreadPool(int corePoolSize)方法,该方法返回ScheduledThreadPoolExecutor实例。 这是Executors类的代码片段。

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}

Below is our java scheduler example program using ScheduledExecutorService and ScheduledThreadPoolExecutor implementation.

下面是我们的Java Scheduler示例程序,它使用ScheduledExecutorServiceScheduledThreadPoolExecutor实现。

package com.journaldev.threads;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class ScheduledThreadPool {

	public static void main(String[] args) throws InterruptedException {
		ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
		
		
		//schedule to run after sometime
		System.out.println("Current Time = "+new Date());
		for(int i=0; i<3; i++){
			Thread.sleep(1000);
			WorkerThread worker = new WorkerThread("do heavy processing");
			scheduledThreadPool.schedule(worker, 10, TimeUnit.SECONDS);
		}
		
		//add some delay to let some threads spawn by scheduler
		Thread.sleep(30000);
		
		scheduledThreadPool.shutdown();
		while(!scheduledThreadPool.isTerminated()){
			//wait for all tasks to finish
		}
		System.out.println("Finished all threads");
	}

}

When we run above java scheduler example program, we get following output that confirms that tasks are running with 10 seconds delay.

当我们在Java Scheduler示例程序上方运行时,将得到以下输出,该输出确认任务正在以10秒的延迟运行。

Current Time = Tue Oct 29 15:10:03 IST 2013
pool-1-thread-1 Start. Time = Tue Oct 29 15:10:14 IST 2013
pool-1-thread-2 Start. Time = Tue Oct 29 15:10:15 IST 2013
pool-1-thread-3 Start. Time = Tue Oct 29 15:10:16 IST 2013
pool-1-thread-1 End. Time = Tue Oct 29 15:10:19 IST 2013
pool-1-thread-2 End. Time = Tue Oct 29 15:10:20 IST 2013
pool-1-thread-3 End. Time = Tue Oct 29 15:10:21 IST 2013
Finished all threads

Note that all the schedule() methods return instance of ScheduledFuture that we can use to get the thread state information and delay time for the thread.

请注意,所有schedule()方法都返回ScheduledFuture实例,我们可以使用该实例获取线程状态信息和线程的延迟时间。

ScheduledFuture extends Future interface, read more about them at Java Callable Future Example.

ScheduledFuture扩展了Future接口,请在Java Callable Future Example上阅读有关它们的更多信息。

There are two more methods in ScheduledExecutorService that provide option to schedule a task to run periodically.

ScheduledExecutorService中还有另外两种方法,它们提供了计划任务定期运行的选项。

ScheduledExecutorService scheduleAtFixedRate(可运行命令,长initialDelay,长周期,TimeUnit单位) (ScheduledExecutorService scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit))

We can use ScheduledExecutorService scheduleAtFixedRate method to schedule a task to run after initial delay and then with the given period.

我们可以使用ScheduledExecutorService scheduleAtFixedRate方法来调度任务,使其在初始延迟之后并在给定时间段内运行。

The time period is from the start of the first thread in the pool, so if you are specifying period as 1 second and your thread runs for 5 second, then the next thread will start executing as soon as the first worker thread finishes it’s execution.

时间段是从池中第一个线程的起点开始的,因此,如果将period指定为1秒,并且线程运行5秒钟,则下一个线程将在第一个工作线程完成执行后立即开始执行。

For example, if we have code like this:

例如,如果我们有这样的代码:

for (int i = 0; i < 3; i++) {
	Thread.sleep(1000);
	WorkerThread worker = new WorkerThread("do heavy processing");
	// schedule task to execute at fixed rate
	scheduledThreadPool.scheduleAtFixedRate(worker, 0, 10,
	TimeUnit.SECONDS);
}

Then we will get output like below.

然后我们将得到如下输出。

Current Time = Tue Oct 29 16:10:00 IST 2013
pool-1-thread-1 Start. Time = Tue Oct 29 16:10:01 IST 2013
pool-1-thread-2 Start. Time = Tue Oct 29 16:10:02 IST 2013
pool-1-thread-3 Start. Time = Tue Oct 29 16:10:03 IST 2013
pool-1-thread-1 End. Time = Tue Oct 29 16:10:06 IST 2013
pool-1-thread-2 End. Time = Tue Oct 29 16:10:07 IST 2013
pool-1-thread-3 End. Time = Tue Oct 29 16:10:08 IST 2013
pool-1-thread-1 Start. Time = Tue Oct 29 16:10:11 IST 2013
pool-1-thread-4 Start. Time = Tue Oct 29 16:10:12 IST 2013

ScheduledExecutorService scheduleWithFixedDelay(可运行命令,长initialDelay,长延迟,TimeUnit单位) (ScheduledExecutorService scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnit unit))

ScheduledExecutorService scheduleWithFixedDelay method can be used to start the periodic execution with initial delay and then execute with given delay. The delay time is from the time thread finishes it’s execution. So if we have code like below:

ScheduledExecutorService scheduleWithFixedDelay方法可用于以初始延迟开始定期执行,然后以给定延迟执行。 延迟时间是从线程完成执行的时间开始。 因此,如果我们有如下代码:

for (int i = 0; i < 3; i++) {
	Thread.sleep(1000);
	WorkerThread worker = new WorkerThread("do heavy processing");
	scheduledThreadPool.scheduleWithFixedDelay(worker, 0, 1,
	TimeUnit.SECONDS);
}

Then we will get output like below.

然后我们将得到如下输出。

Current Time = Tue Oct 29 16:14:13 IST 2013
pool-1-thread-1 Start. Time = Tue Oct 29 16:14:14 IST 2013
pool-1-thread-2 Start. Time = Tue Oct 29 16:14:15 IST 2013
pool-1-thread-3 Start. Time = Tue Oct 29 16:14:16 IST 2013
pool-1-thread-1 End. Time = Tue Oct 29 16:14:19 IST 2013
pool-1-thread-2 End. Time = Tue Oct 29 16:14:20 IST 2013
pool-1-thread-1 Start. Time = Tue Oct 29 16:14:20 IST 2013
pool-1-thread-3 End. Time = Tue Oct 29 16:14:21 IST 2013
pool-1-thread-4 Start. Time = Tue Oct 29 16:14:21 IST 2013

That’s all for java scheduler example. We learned about ScheduledExecutorService and ScheduledThreadPoolExecutorthread too. You should check other articles about Multithreading in Java.

Java调度程序示例就这些了。 我们也了解了ScheduledExecutorService和ScheduledThreadPoolExecutorthread。 您应该查看有关Java多线程的其他文章。

References:

参考文献:

翻译自: https://www.journaldev.com/2340/java-scheduler-scheduledexecutorservice-scheduledthreadpoolexecutor-example

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java原生的ScheduledExecutorService是一个用于定时执行任务的接口,它是ExecutorService的子接口。它提供了一种方便的方式来执行定时任务,可以在指定的时间间隔内重复执行任务,也可以在指定的延迟时间后执行任务。 下面是一个简单的封装示例: ```java import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class TaskScheduler { private ScheduledExecutorService executorService; public TaskScheduler() { executorService = Executors.newScheduledThreadPool(1); } public void scheduleTask(Runnable task, long initialDelay, long period) { executorService.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.MILLISECONDS); } public void stop() { executorService.shutdown(); } } ``` 在上面的示例中,我们创建了一个TaskScheduler类来封装ScheduledExecutorService。它使用了Executors类的newScheduledThreadPool方法来创建一个ScheduledExecutorService实例。 scheduleTask方法用于添加定时任务,它接受一个Runnable对象作为任务,以及初始延迟时间和重复执行的时间间隔。任务将在初始延迟时间后开始执行,并且每隔指定的时间间隔重复执行。 stop方法用于停止定时任务的执行,它调用了ScheduledExecutorService的shutdown方法来关闭线程池。 使用示例: ```java public class Main { public static void main(String[] args) { TaskScheduler scheduler = new TaskScheduler(); Runnable task = () -> { // 执行任务的逻辑 System.out.println("Task executed"); }; scheduler.scheduleTask(task, 0, 1000); // 每隔1秒执行一次任务 // 等待一段时间后停止任务的执行 try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } scheduler.stop(); } } ``` 上面的示例中,我们创建了一个TaskScheduler实例,并定义了一个任务task,然后使用scheduleTask方法将任务添加到定时任务中。任务将每隔1秒执行一次。在等待5秒后,我们调用stop方法停止任务的执行。 希望以上内容能够帮助到你。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值