java 周期执行_java ScheduledExecutorService 执行周期性任务

ScheduledExecutorService 是jdk1.5之后提供的替代Timer的一个类。下面为大家提供一个简单的使用例子。

使用ScheduledExecutorService 需注意一点,如果执行过程中一点有一个任务发现异常,程序会终止执行。因此最好自己将异常捕获处理掉。

下面是jdk中的注释:

Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next. If any execution of the task encounters an exception, subsequent executions are suppressed. Otherwise, the task will only terminate via cancellation or termination of the executor.

示例如下,ScheduledExecutorService 提供了很多方法,这里只说明一种:

import java.time.LocalDateTime;

import java.time.format.DateTimeFormatter;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.ScheduledThreadPoolExecutor;

import java.util.concurrent.TimeUnit;

public class Test implements Runnable {

private static LocalDateTime ldt = LocalDateTime.now();

private static DateTimeFormatter dtf = DateTimeFormatter

.ofPattern("yyyy-MM-dd hh:mm:ss");

public static void main(String[] args) {

ScheduledExecutorService ses = new ScheduledThreadPoolExecutor(2);

Test test1 = new Test();

// 第一个参数:需要执行的任务,第二个参数:第一次执行延迟的时间,

// 第三个参数:间隔时间,第四个参数:计量单位,这里选择秒

ses.scheduleAtFixedRate(test1, 1, 2, TimeUnit.SECONDS);

System.out.println(ldt.format(dtf));

}

@Override

public void run() {

try {

LocalDateTime ldt = LocalDateTime.now();

DateTimeFormatter dtf = DateTimeFormatter

.ofPattern("yyyy-MM-dd hh:mm:ss");

System.out.println(ldt.format(dtf) + "执行");

} catch (Exception e) {

e.printStackTrace();

}

}

}

运行结果:

19da4371c4a0

演示.gif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ScheduledExecutorServiceJava中的一个接口,它是ExecutorService的子接口,用于在指定的时间间隔内执行任务。它可以用来执行定时任务周期性任务以及延迟任务。 要获取ScheduledExecutorService任务的返回结果,可以使用Future接口。Future接口表示一个异步计算的结果,可以通过它来获取任务执行结果。 首先,我们需要使用ScheduledExecutorService的submit方法来提交任务,并将返回的Future对象保存起来。然后,可以使用Future对象的get方法来获取任务的返回结果。get方法是一个阻塞方法,会一直等待任务执行完成并返回结果。 下面是一个示例代码: ```java import java.util.concurrent.*; public class ScheduledExecutorServiceExample { public static void main(String[] args) throws InterruptedException, ExecutionException { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); // 提交任务并获取Future对象 Future<String> future = executor.schedule(() -> { // 任务逻辑 return "Hello, World!"; }, 1, TimeUnit.SECONDS); // 获取任务的返回结果 String result = future.get(); System.out.println(result); executor.shutdown(); } } ``` 在上面的示例中,我们创建了一个ScheduledExecutorService对象,并使用schedule方法提交了一个任务。该任务会在1秒后执行,并返回字符串"Hello, World!"。然后,我们使用Future对象的get方法获取任务的返回结果,并打印输出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值